jdk7的try-with-resources
JDK1.7开始,java引入了 try-with-resources 声明,将 try-catch-finally 简化为 try-catch,这其实是一种语法糖,在编译时会进行转化为 try-catch-finally 语句。新的声明包含三部分:try-with-resources 声明、try 块、catch 块。它要求在 try-with-resources 声明中定义的变量实现了 AutoCloseable 接口,这样在系统可以自动调用它们的close方法,从而替代了finally中关闭资源的功能。
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Test public void TestForTryWithResources() { try (InputStream inputStream = new FileInputStream("/test.md"); //InputStream inputStream = TryCatchDemo.class.getResourceAsStream("/test.md") BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream)) ) { StringBuilder sb = new StringBuilder(); String tmpString = null; while ((tmpString = bf.readLine()) != null) {//抛出IOException的地方 sb.append(tmpString); } System.out.println(sb.toString()); } catch (IOException e) { e.printStackTrace(); } }
|
它的结构是try(){}
因为括号里头的InputStream ,BufferedReader 都实现了一个AutoCloseable接口,所以无论这段代码是正常执行完,还是有异常往外抛,还是内部代码块发生异常被截获,最终都会按照创建资源的逆顺序,自动关闭资源.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @Test public void AutoCloseTest() { try (AutoCloseAbleBean autoCloseable = new AutoCloseAbleBean()) { throw new RuntimeException("test"); // autoCloseable.dosomething(); // return; } catch (Exception e) { e.printStackTrace(); // throw new RuntimeException("test"); }finally { throw new RuntimeException("test"); } }
class AutoCloseAbleBean implements AutoCloseable { @Override public void close() throws Exception { System.out.println("i am close"); } void dosomething() { System.out.println("before close"); } }
|
异常机制的变化
它们的异常抛出机制发生了变化。在过去的 try-catch-finally 结构中,我们在finally块中关闭资源通常是这样的:
1 2 3 4 5 6 7 8 9 10 11 12
| catch (Exception e) { e.printStackTrace(); // 第一处异常处理 } finally { try { if (c != null) { c.close(); } } catch (IOException e) { e.printStackTrace(); // 第二处异常处理 } }
|
异常处理有两种情况:
try 块没有发生异常时,直接调用finally块,如果 close 发生异常,就处理。
try 块发生异常,catch 块捕捉,进行第一处异常处理,然后调用 finally 块,如果 close 发生异常,就进行第二处异常处理。
但是在 try-with-resources 结构中,异常处理也有两种情况(注意,不论 try 中是否有异常,都会首先自动执行 close 方法,然后才判断是否进入 catch 块,建议阅读后面的反编译代码):
try 块没有发生异常时,自动调用 close 方法,如果发生异常,catch 块捕捉并处理异常。
try 块发生异常,然后自动调用 close 方法,如果 close 也发生异常,catch 块只会捕捉 try 块抛出的异常,close 方法的异常会在catch 中被压制,但是你可以在catch块中,用 Throwable.getSuppressed 方法来获取到压制异常的数组。
我们可以通过自定义的 AutoCloseable 类来理解这个过程。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| public class Main {
public static void startTest() { try (MyAutoCloseA a = new MyAutoCloseA(); MyAutoCloseB b = new MyAutoCloseB()) { a.test(); b.test(); } catch (Exception e) { System.out.println("Main: 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(); } }
/* 输出为: MyAutoCloaseA: test() MyAutoCloseB: on close MyAutoCloseA: on close() Main: exception MyAutoCloaseA: test() IOException MyAutoCloaseB: close() ClassNotFoundException MyAutoCloaseA: close() ClassNotFoundException */
class MyAutoCloseA implements AutoCloseable {
public void test() throws IOException { System.out.println("MyAutoCloaseA: test()"); throw new IOException("MyAutoCloaseA: test() IOException"); }
@Override public void close() throws Exception { System.out.println("MyAutoCloseA: on close()"); throw new ClassNotFoundException("MyAutoCloaseA: close() ClassNotFoundException"); } }
class MyAutoCloseB implements AutoCloseable {
public void test() throws IOException { System.out.println("MyAutoCloaseB: test()"); throw new IOException("MyAutoCloaseB: test() IOException"); } @Override public void close() throws Exception { System.out.println("MyAutoCloseB: on close"); throw new ClassNotFoundException("MyAutoCloaseB: close() ClassNotFoundException"); } }
|
通过反编译class文件,可以看到实际的执行过程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| public static void startTest() { try { MyAutoCloseA a = new MyAutoCloseA(); Throwable var33 = null;
try { MyAutoCloseB b = new MyAutoCloseB(); Throwable var3 = null;
try { // 我们定义的 try 块 a.test(); b.test(); } catch (Throwable var28) { // try 块中抛出的异常 var3 = var28; throw var28; } finally { if (b != null) { // 如果 try 块中抛出异常,就将 close 中的异常(如果有)附加为压制异常 if (var3 != null) { try { b.close(); } catch (Throwable var27) { var3.addSuppressed(var27); } } else { // 如果 try 块没有抛出异常,就直接关闭,可能会抛出关闭异常 b.close(); } }
} } catch (Throwable var30) { var33 = var30; throw var30; } finally { if (a != null) { if (var33 != null) { try { a.close(); } catch (Throwable var26) { var33.addSuppressed(var26); } } else { a.close(); } }
} // 所有的异常在这里交给 catch 块处理 } catch (Exception var32) { // 我们定义的 catch 块 System.out.println("Main: exception"); System.out.println(var32.getMessage()); Throwable[] suppressed = var32.getSuppressed();
for(int i = 0; i < suppressed.length; ++i) { System.out.println(suppressed[i].getMessage()); } }
}
|
1 2 3 4 5
| 我还想补充的是:
catch 块中,看不到 try-with-recourse 声明中的变量。 try-with-recourse 中,try 块中抛出的异常,在 e.getMessage() 可以获得,而调用 close() 方法抛出的异常在e.getSuppressed() 获得。 try-with-recourse 中定义多个变量时,由反编译可知,关闭的顺序是从后往前。
|
参考来源
1.https://www.jianshu.com/p/8e4421aff0a6
2.https://blog.csdn.net/weixin_40255793/article/details/80812961