Say 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 that myResource1.close()
will be called?
For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.
The close() method of objects declared in a try with resources block is invoked regardless of whether an exception is thrown during execution.
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.
Generally finally block is used to close all the resources (viz., file, database connection, socket or anything that should be closed after its task is done) to prevent any leaks.
Yes, this is guaranteed. Quoting from 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.
In this case, if the second new MyResource()
throws an exception, since myResource1
was successfully initialized, it will be closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With