I'm wondering if putting a return statement inside a try-with-resources block prevents the resource to be automatically closed.
try(Connection conn = ...) { return conn.createStatement().execute("..."); }
If I write something like this will the Connection be closed? In the Oracle documentation it is stated that:
The try-with-resources statement ensures that each resource is closed at the end of the statement.
What happens if the end of the statement is never reached because of a return 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.
A resource is an object to be closed at the end of the program. As seen from the above syntax, we declare the try-with-resources statement by, declaring and instantiating the resource within the try clause. specifying and handling all exceptions that might be thrown while closing the resource.
Benefits of using try-with-resources: More readable code and easy to write. Automatic resource management. Number of lines of code is reduced.
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.
Based on Oracle's tutorial, "[the resource] will be closed regardless of whether the try statement completes normally or abruptly". It defines abruptly
as from an exception.
Returning inside the try
is an example of abrupt completion, as defined by JLS 14.1.
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