Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception thrown during try-with-resources declaration

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?

like image 697
Charles Spencer Avatar asked Feb 26 '16 20:02

Charles Spencer


People also ask

Does try with resources Throw exception?

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.

Does try with resources close on exception?

The close() method of objects declared in a try with resources block is invoked regardless of whether an exception is thrown during execution.

What is try with resources statement?

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.

What are the resources used in exception handling?

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.


1 Answers

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.

like image 55
Tunaki Avatar answered Oct 19 '22 00:10

Tunaki