Try-With-Recourse
try-with-recourse的写法相对于try-catch-finally更简洁,对比如下:
try-catch-finally
import java.io.*;
public class MessyExceptions {
public static void main(String[] args) {
InputStream in = null;
try {
in = new FileInputStream(new File("MessyExceptions.java"));
int contents = in.read();
} catch(IOException e) {
// Handle the error
} finally {
if(in != null) {
try {
in.close();
} catch(IOException e) {
// Handle the close() error
}
}
}
}
}
try-with-recourse
import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
try(
InputStream in = new FileInputStream(new File("TryWithResources.java"))
) {
int contents = in.read();
// Process contents
} catch(IOException e) {
// Handle the error
}
}
}
显然try-with-recourse简洁得多,它会按照申明顺序自动释放()中的资源。
- 工作原理
try-with-resources 定义子句中创建的对象(在括号内)必须实现 java.lang.AutoCloseable 接口,这个接口只有一个方法:close()。当在 Java 7 中引入 AutoCloseable 时,许多接口和类被修改以实现它,如:Stream 对象 。
Java 5 中的 Closeable 已经被修改,修改之后的接口继承了 AutoCloseable 接口。所以所有实现了 Closeable 接口的对象,都支持了 try-with-resources 特性。
- 注意:
- catch 块中,看不到 try-with-recourse 声明中的变量;
- try-with-recourse 中,try 块中抛出的异常,在 e.getMessage() 可以获得,而调用 close() 方法抛出的异常在e.getSuppressed() 获得;
- try-with-recourse 中定义多个变量时,由反编译可知,关闭的顺序是从后往前。
自定义异常
package com.cq.common.exception;
/**
* 自定义运行时异常类
* 一般在业务层逻辑出现问题时抛出
*/
public class MyException extends RuntimeException {
/**
* 错误状态码
* - 暂时用不着
*/
private Integer errorCode;
/**
* 错误信息
*/
private String errorMsg;
public MyException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
public MyException(Throwable trace) {
super(trace);
}
public MyException(String errorMsg, Throwable trace) {
super(errorMsg, trace);
}
public String getErrorMsg() {
return this.errorMsg;
}
}