Java – throw an exception during the try with resources declaration

Suppose I have the following try with resources statement in Java:

try (MyResource myResource1 = new MyResource(); MyResource myResource2 = new MyResource()) {
    // do stuff...
}

If myresource myresource2 = new myresource() throws an exception, is it guaranteed to call myresource1 close()?

Solution

Yes, it's guaranteed Quoted from JLS section 14.20 3:

In this case, if the second new myresource () throws an exception, because myresource1 has been successfully initialized, it will be closed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>