try-with-resources声明
JDK1.7开始,java引入了 try-with-resources 声明,将 try-catch-finally 简化为 try-catch;
1、新的声明包含三部分:try-with-resources 声明、try 块、catch 块;
2、要求在 try-with-resources 声明中定义的变量实现了 AutoCloseable 接口,这样在系统可以自动调用它们的close方法,从而替代了finally中关闭资源的功能。
try-catch-finally 异常处理有两种情况:
- try 块没有发生异常时,直接调用finally块,如果 close 发生异常,就处理。
- try 块发生异常,catch 块捕捉,进行第一处异常处理,然后调用 finally 块,如果 close 发生异常,就进行第二处异常处理。
try-with-resources 结构中,异常处理也有两种情况:
- try 块没有发生异常时,自动调用 close 方法,如果发生异常,catch 块捕捉并处理异常。
- try 块发生异常,然后自动调用 close 方法(所有close()都执行),如果 close 也发生异常,catch 块只会捕捉 try 块抛出的异常,close 方法的异常会在catch 中被压制,但是你可以在catch块中,用 Throwable.getSuppressed 方法来获取到压制异常的数组。
- 任何 catch 或 finally 块在声明的资源 后再执行。
public class TestTWR {
public static void startTest() {
try (MyAutoCloseA a = new MyAutoCloseA();
MyAutoCloseB b = new MyAutoCloseB()) {
a.test();
b.test();
} catch (Exception e) {
System.out.println("TestTWR: exception");
System.out.println(e.getMessage());
Throwable[] suppressed = e.getSuppressed();
for (int i = 0; i < suppressed.length; i++)
System.out.println(suppressed[i].getMessage());
}
}
public static void main(String[] args) throws Exception {
startTest();
}
}
/* 输出为:
ResourceA: test()
ResourceB: on close
ResourceA: on close()
TestTWR: exception
ResourceA: test() IOException
ResourceB: close() ClassNotFoundException
ResourceA: close() ClassNotFoundException
*/
class ResourceA implements AutoCloseable {
public void test() throws IOException {
System.out.println("ResourceA: test()");
throw new IOException("ResourceA: test() IOException");
}
@Override
public void close() throws Exception {
System.out.println("ResourceA: on close()");
throw new ClassNotFoundException("ResourceA: close() ClassNotFoundException");
}
}
class ResourceB implements AutoCloseable {
public void test() throws IOException {
System.out.println("ResourceB: test()");
throw new IOException("ResourceB: test() IOException");
}
@Override
public void close() throws Exception {
System.out.println("ResourceB: on close");
throw new ClassNotFoundException("ResourceB: close() ClassNotFoundException");
}
}
总结:
- catch 块中,看不到 try-with-recourse 声明中的变量。
- try-with-recourse 中,try 块中抛出的异常,在 e.getMessage() 可以获得,而调用 close() 方法抛出的异常在e.getSuppressed() 获得。
- try-with-recourse 中定义多个变量时,使用分号分割,
关闭的顺序是从后往前,并且全部关闭
。