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

java中的try-with-resource

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

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.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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