栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

try-with-resources

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();
        }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/940930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号