JDK1.8中的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中关闭资源的功能。

但是,它们的异常抛出机制发生了变化。在过去的 try-catch-finally 结构中,我们在finally块中关闭资源通常是这样的:

catch (Exception e) {
	e.printStackTrace(); // 第一处异常处理
}
finally {
    try {
        if (c != null) {
            c.close();
        }
    } catch (IOException e) {
        e.printStackTrace(); // 第二处异常处理
    }
}

异常处理有两种情况:

  1. try 块没有发生异常时,直接调用finally块,如果 close 发生异常,就处理。
  2. try 块发生异常,catch 块捕捉,进行第一处异常处理,然后调用 finally 块,如果 close 发生异常,就进行第二处异常处理。

但是在 try-with-resources 结构中,异常处理也有两种情况(注意,不论 try 中是否有异常,都会首先自动执行 close 方法,然后才判断是否进入 catch 块,建议阅读后面的反编译代码):

  1. try 块没有发生异常时,自动调用 close 方法,如果发生异常,catch 块捕捉并处理异常。
  2. try 块发生异常,然后自动调用 close 方法,如果 close 也发生异常,catch 块只会捕捉 try 块抛出的异常,close 方法的异常会在catch 中被压制,但是你可以在catch块中,用 Throwable.getSuppressed 方法来获取到压制异常的数组。

我们可以通过自定义的 AutoCloseable 类来理解这个过程。

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文件,可以看到实际的执行过程:

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. catch 块中,看不到 try-with-recourse 声明中的变量。
  2. try-with-recourse 中,try 块中抛出的异常,在 e.getMessage() 可以获得,而调用 close() 方法抛出的异常在e.getSuppressed() 获得。
  3. try-with-recourse 中定义多个变量时,由反编译可知,关闭的顺序是从后往前。

参考资料

  1. The try-with-resources Statement
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值