Java – throw an exception during the try with resources declaration
•
Java
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
二维码