加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在try-with-resources声明期间抛出异常

发布时间:2020-12-15 02:55:36 所属栏目:Java 来源:网络整理
导读:假设我在 Java中有以下try-with-resources语句: try (MyResource myResource1 = new MyResource(); MyResource myResource2 = new MyResource()) { // do stuff...} 如果MyResource myResource2 = new MyResource()抛出异常,是否可以保证调用myResource1.cl
假设我在 Java中有以下try-with-resources语句:
try (MyResource myResource1 = new MyResource(); MyResource myResource2 = new MyResource()) {
    // do stuff...
}

如果MyResource myResource2 = new MyResource()抛出异常,是否可以保证调用myResource1.close()?

解决方法

是的,这是有保证的.引自 JLS section 14.20.3:

Resources are initialized in left-to-right order. If a resource fails to initialize (that is,its initializer expression throws an exception),then all resources initialized so far by the try-with-resources statement are closed. If all resources initialize successfully,the try block executes as normal and then all non-null resources of the try-with-resources statement are closed.

在这种情况下,如果第二个新的MyResource()抛出异常,因为myResource1已成功初始化,它将被关闭.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读