try-with-resources

try-with-resources

  1. try-catch-finally的语法糖,java7首次提供。
  2. 使用到的资源需要需要实现AutoCloseable接口。
  3. 可以简化try-catch-finally的写法,将资源关闭的代码隐藏。
  4. 作为语法糖,仅起到简化代码的作用。
  5. 目前还是很少使用这种写法,更多的还是使用原始的try-catch-finally写法。
  6. 以上仅个人看法。
  • 常规的try-catch-finally
        InputStream in = null;
        try {
            in = new FileInputStream(new File("D://test.txt"));
            int len = in.read();
            System.out.println(len);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally {
            if (in != null)
            {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

代码较多,尤其是finally块中,对资源的关闭的写法比较累赘。

  • 使用try-with-resources
        try (InputStream in = new FileInputStream(new File("D://test.txt")))
        {
            int len = in.read();
            System.out.println(len);
        } catch (IOException e) {
            e.printStackTrace();
        }

代码量明显减少,也易于理解,尤其是之前那些累赘代码消失了。

  • try-with-resources本质
        try {
            InputStream in = new FileInputStream(new File("D://test.txt"));

            try {
                int len = in.read();
                System.out.println(len);
            } catch (Throwable var5) {
                try {
                    in.close();
                } catch (Throwable var4) {
                    var5.addSuppressed(var4);
                }

                throw var5;
            }

            in.close();
        } catch (IOException var6) {
            var6.printStackTrace();
        }

上面的代码为编译后的try-with-resources代码,即语法糖的本质代码,这个代码看起来并不整洁。尤其第二层的try-catch-finally代码块。鉴于此,个人更喜欢以下代码:

Throwable类的addSuppressed方法:是java7新增的,用于传递被抑制的异常。白话讲就是说,var5中添加了var4的异常信息,在var5抛出后,捕获者可以得到var4和var5的信息。如果不这么处理,将 var5.addSuppressed(var4); 代码改为 throw var4;或者throw var5;,都只能得到二者之一的信息,另一个信息丢失了。

        try {
            InputStream in = new FileInputStream(new File("D://test.txt"));
            int len = in.read();
            System.out.println(len);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值