java中的try-with-resource

JDK7 开始新增了对需要关闭资源处理的特殊语法 try-with-resource

try(资源变量=创建资源对象){
    
}catch(){
    
}

其中资源对象需要实现接口AutoCloseable,例如 InputStream, OutputStream ,Connection, Statement, ResultSet等接口都实现了,使用 try-with-resource可以不用写finally块,编译器会帮助生成关闭资源的代码,例如:

public static void main(String[] args) {
        try(InputStream is=new FileInputStream("d.txt")) {
            System.out.println(is);
        }catch (IOException e){
            e.printStackTrace();
        }
}

会被转换为

  public static void main(String[] args) {
        try {
            InputStream is = new FileInputStream("d.txt");
            Throwable var2 = null;

            try {
                System.out.println(is.read());
            } catch (Throwable var12) {
                var2 = var12;
                throw var12;
            } finally {
                //判断了资源不为空
                if (is != null) {
                    //如果我们代码有异常,作为压制异常被添加
                    if (var2 != null) {
                        try {
                            is.close();
                        } catch (Throwable var11) {
                            如果close出现异常
                            var2.addSuppressed(var11);
                        }
                    } else {
                        //如果我们代码没有异常,close出现的异常就是最后Catch块中的e
                        is.close();
                    }
                }

            }
        } catch (IOException var14) {
            var14.printStackTrace();
        }

    }

这是编译器帮我们生成的关闭资源的代码,我们就可以不用写finally块来关闭资源,(反正我自己写finally来关闭资源的时候没考虑这么多的 ,哈哈!所以交给编译器不好吗!)
其中,为什么要设计一个addSuppressed(Throwable e)(添加压制异常) 的方法呢?是为了防止异常信息的丢失

栗子↓:

static class MyResource implements AutoCloseable{
        @Override
        public void close() throws Exception {
            throw new Exception("close 异常");
        }
    }
    public static void main(String[] args) {
        try(MyResource myResource=new MyResource()) {
            int i=1/0;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

运行的结果为:

java.lang.ArithmeticException: / by zero
	at testJvm.helloWorld.main(helloWorld.java:22)
	Suppressed: java.lang.Exception: close 异常
		at testJvm.helloWorld$MyResource.close(helloWorld.java:17)
		at testJvm.helloWorld.main(helloWorld.java:23)

可以看到,我们的两个异常信息都不会丢失

有错误望指正
本文章参考:黑马程序员JVM.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值