Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-with-resources and return statements in java

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?

like image 943
maff Avatar asked Apr 08 '14 20:04

maff


People also ask

What is the try with resources statement in Java?

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.

How do you write to try with resources?

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.

What is the advantage of using try with resources statement?

Benefits of using try-with-resources: More readable code and easy to write. Automatic resource management. Number of lines of code is reduced.

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.


1 Answers

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.

like image 146
merlin2011 Avatar answered Oct 02 '22 21:10

merlin2011