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

前端之家收集整理的这篇文章主要介绍了java – 在try-with-resources声明期间抛出异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我在 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已成功初始化,它将被关闭.

原文链接:https://www.f2er.com/java/128238.html

猜你在找的Java相关文章