Java Try with Resources With Examples

Today we will look into Java Try with Resources. One of the Java 7 feature is try-with-resources statement for automatic resource management.

Try with Resources

A resource is an object that must be closed once your program is done using it. For example, a File resource or JDBC resource for a database connection or a Socket connection resource. Before Java 7, there was no auto resource management and we should explicitly close the resource once our work is done with it. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks and performance hit when we forgot to close the resource.

Let’s see a pseudo code snippet to understand this java try with resources feature.

Before Java 7:

Java 7 try with resources implementation:

Let’s write a simple program to read a file and print the first line using Java 6 or older versions and Java 7 try-with-resources implementation.

Java 6 Resource Management Example

Java 7 Try With Resources Example

Java try with resources benefits

Some of the benefits of using try with resources in java are;

  1. More readable code and easy to write.
  2. Automatic resource management.
  3. Number of lines of code is reduced.
  4. No need of finally block just to close the resources.
  5. We can open multiple resources in try-with-resources statement separated by a semicolon. For example, we can write following code:
  6. When multiple resources are opened in try-with-resources, it closes them in the reverse order to avoid any dependency issue. You can extend my resource program to prove that.

Java 7 has introduced a new interface java.lang.AutoCloseable. To use any resource in try-with-resources, it must implement AutoCloseable interface else java compiler will throw compilation error.

Lets confirm this with an example:

The output of the above program is:

From the output, it’s clear that as soon as the try-catch block is finished, the resource close method is called.

Try with Resources Exceptions

There is one difference to note between try-catch-finally and try-with-resources in case of exceptions.

If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block.

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.

To better clarify this difference, we will see sample code.

The output of the above program is:

The output of the program proves the difference given above. That’s all for the Java 7 try-with-resources.

By admin

Leave a Reply

%d bloggers like this: