Java — Auto Close Your Resources with Try-With-Resource
By: Dulitha Dabare
Tags: Best Practices, Java, Android, Programming

Usually, when you need to close a resource you’ve been using in Java, you would turn to the trusty finally block and close all of your opened resources inside the finally block.

Why You Need To Always Close Your Open Resources

For example, let’s say that you are using a java.sql.Connection object to connect to your database, a java.sql.PreparedStatement object to prepare your SQL query and a java.sql.ResultSet object to capture your returned result from the database query.

Naturally, because you are an in the ideal mind zone, you would remember to close the java.sql.Connection object, java.sql.PreparedStatement object and the java.sql.ResultSet object in the finally block as shown in the below code snippet.

Connection con; PreparedStatement ps = null; ResultSet rs = null; try { // your code with database connections } catch ( Exception e ) { //Catch and handle any exceptions } finally { con.close(); ps.close(); rs.close(); }

Note : While closing java.sql.ResultSet object is not explicitly required (because a j ava.sql.ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results according to Java documentation about java.sql.ResultSet ) it is best practice to close the ResultSet object manually because some JDBC drivers tend to fail when closing the ResultSet object automatically.

But what will happen if you forget to close one of the database connections you’ve opened and used? Your application will keep the database connection open and prevent any new connections from being opened if the database open connection limit has been exceeded. This can result in critical failures in your application and it can result in very hard-to-pinpoint errors in your system.

This is where the new try-with-resources statement introduced with Java 7 will come to the rescue.

The usage of try-with-resources is basically this: You can declare all of the closable resource objects you are going to use inside the try clause and Java will take care of closing the resources all by itself.

try ( Connection con = getConnection(); PreparedStatement ps = null; ResultSet resultSet = null; ) { // your code with database connections }

catch ( Exception e ) { //Catch and handle any exceptions } finally { // Instead of closing open resources, you can do anything else in here }

Note that only objects which implement java.lang.AutoCloseable can be used with the try-with-resources statement. This includes all the classes which implement java.io.Closeable .

And Another Thing

Another advantage of using the try-with-resources statement is the ability prevent Exception Masking.

Let’s take the following example.

We have a myMethod() with a regular try /finally block for handling resource objects. And we have a main method which catches the exception being thrown by the myMethod() .

In the myMethod() , there are two exception which can be thrown.

1. ExceptionType1 thrown in the try block.

2. ExceptionType2 thrown in the when trying to close the resource.

public static void myMethod() throws Exception()

{ Closeable resource = null; try { // your code which throws ExceptionType1 } finally { resource.close();

// an exception of type ExceptionType1 will be thrown when trying to close the resource } }

And an example where you use the above method.

public static void main(String[] args) { try { myMethod(); } catch( Exception e) { e.printStackTrace(); } }

In the above scenario, where an exception is being thrown in the try block and in the finally block, the catch block will only receive the ExceptionType2 exception. I.e., ExceptionType1 thrown first will get masked by the ExceptionType2 thrown second.

So how do we identify the exception thrown by our code block?

This is where the try-with-resources statement comes to our rescue. Let’s analyze the above scenario while using a try-with-resource statement.

The main exception ExceptionType1 we need is first thrown by the code block. Then, the second exception ExceptionType2 gets thrown when Java tries to close the resources.

But the difference is that the second exception will get suppressed and added to main exception ExceptionType1, as a suppressed exception.The main exception ExceptionType1 is then presented to the catch block of the main() method.

I.e., if we structure our myMethod() as shown below, the exception caught in the catch block will be the ExceptionType1 with the ExceptionType2 added as a suppressed exception. That way, we catch the exception we need, without it being masked by a later exception.

public static void myMethod() throws Exception() { try ( Closeable resource = null; ) { // your code which throws ExceptionType1 } }

Conclusion

By using try-with-resources statements in your code to manage resources, you will end up with safe, easier to read code, that can also handle exceptions in an intuitive manner.

For more information on the usages of the try-with-resources statement and on how exceptions are handled inside the try-with-resources statement, visit