Try with resource

Try-with-resources in Java 7 is a new way of exception handling which makes it easier to automatically close resources that are used within a try-catch block.

A resource is an object that must be closed after using it.

Example : A file resource for file IO operations, JDBC resource for database connection etc.

Before this feature introduced in Java 7, there was no auto resource management in java and we had to explicitly close the resource after using the resource.

Generally, we do that in the finally block of a try-catch statement.

This approach was causing lot of memory leaks and performance hit when we forgot to close the resource.

Let’s look at the below example

  1. private static void readFile() throws IOException {
  2.     InputStream input = null;
  3.  
  4.     try {
  5.         input = new FileInputStream("sample.txt");
  6.  
  7.         int data = input.read();
  8.         while(data != -1){
  9.             System.out.print((char) data);
  10.             data = input.read();
  11.         }
  12.     } finally {
  13.         if(input != null){
  14.             input.close();
  15.         }
  16.     }
  17. }
private static void readFile() throws IOException {
    InputStream input = null;

    try {
        input = new FileInputStream("sample.txt");

        int data = input.read();
        while(data != -1){
            System.out.print((char) data);
            data = input.read();
        }
    } finally {
        if(input != null){
            input.close();
        }
    }
}


In the above program, we can see that exception might be thrown in try block in few places like while opening and reading the file

We have used finally block to close resources, it will make sure that code will always be executed no matter exception occurs or not.
If an exception is thrown in the try block then finally block will be executed to close the resource.

What if an exception occurs in finally block while closing the resource?


The exception thrown from the finally block would be propagated to the caller, even though the exception thrown from the try block is more relevant to propagate.

This will kill the actual root cause of exception and throw other exception from finally block.

Let’s do the same in Java 7 try with resource


In Java 7 we can write the above code using try-with-resource construct like this:

  1. private static void readFileJava7() throws IOException {
  2.  
  3.     try(FileInputStream input = new FileInputStream("file.txt")) {
  4.  
  5.         int data = input.read();
  6.         while(data != -1){
  7.             System.out.print((char) data);
  8.             data = input.read();
  9.         }
  10.     }
  11. }
private static void readFileJava7() throws IOException {

    try(FileInputStream input = new FileInputStream("file.txt")) {

        int data = input.read();
        while(data != -1){
            System.out.print((char) data);
            data = input.read();
        }
    }
}

We can see that the way try block is started,

    try(FileInputStream input = new FileInputStream("file.txt")) {

This way of writing “try” is called try-with-resources


The FileInputStream variable is instantiated and assigned to the variable inside try parenthesis

When the try block completes execution, the FileInputStream will be closed automatically.

This is possible because FileInputStream implements the Java interface java.lang.AutoCloseable.

All classes implementing this interface can be used inside the try-with-resources construct and it will be closed automatically by Java.

So this way, we don’t even need to write finally block to close the resource.

Even if we forget to close resources, Java takes care of it.

We can also use multiple resources within try as below

  1. private static void readFileJava7() throws IOException {
  2.  
  3.     try(  FileInputStream input = new FileInputStream("file.txt");
  4.           BufferedInputStream bufferedInputStream = new BufferedInputStream(input)
  5.     )
  6.  {
  7.  
  8.         int data = bufferedInputStream.read();
  9.         while(data != -1){
  10.             System.out.print((char) data);
  11.     data = bufferedInputStream.read();
  12.         }
  13.     }
  14. }
private static void readFileJava7() throws IOException {

    try(  FileInputStream input = new FileInputStream("file.txt");
          BufferedInputStream bufferedInputStream = new BufferedInputStream(input)
    )
 {

        int data = bufferedInputStream.read();
        while(data != -1){
            System.out.print((char) data);
    data = bufferedInputStream.read();
        }
    }
}


The above program creates 2 resources inside the parentheses after the try keyword.
1. FileInputStream
2. BufferedInputStream.

Both of these resources will be closed automatically when try block completes execution.

Note :
The resources will be closed in reverse order of the order in which they are created inside the try parentheses. So in above example, First the BufferedInputStream will be closed, then the FileInputStream will be closed.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on