假设我在
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已成功初始化,它将被关闭.