Java Try with Resources

Filed Under: Java

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

try with resources, java 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:


try{
	//open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {
	// Exception handling like FileNotFoundException, IOException etc
}finally{
	// close resources
}

Java 7 try with resources implementation:


try(// open resources here){
    // use resources
} catch (FileNotFoundException e) {
	// exception handling
}
// resources are closed as soon as try-catch block is executed.

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


package com.journaldev.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Java6ResourceManagement {

	public static void main(String[] args) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("C:\\journaldev.txt"));
			System.out.println(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}

Java 7 Try With Resources Example


package com.journaldev.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Java7ResourceManagement {

	public static void main(String[] args) {
		try (BufferedReader br = new BufferedReader(new FileReader(
				"C:\\journaldev.txt"))) {
			System.out.println(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

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:
    
    try (BufferedReader br = new BufferedReader(new FileReader(
    				"C:\\journaldev.txt"));
    				java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(FileSystems.getDefault().getPath("C:\\journaldev.txt"), Charset.defaultCharset())) {
    			System.out.println(br.readLine());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    
  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:


package com.journaldev.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;

public class Java7ResourceManagement {

	public static void main(String[] args) {

		try (MyResource mr = new MyResource()) {
			System.out.println("MyResource created in try-with-resources");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("Out of try-catch block.");
	}

	static class MyResource implements AutoCloseable{

		@Override
		public void close() throws Exception {
			System.out.println("Closing MyResource");
		}

	}
}

The output of the above program is:


MyResource created in try-with-resources
Closing MyResource
Out of try-catch block.

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.


package com.journaldev.util;

public class Java7ResourceManagement {

	public static void main(String[] args) throws Exception {
		try {
			tryWithResourceException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		try {
			normalTryException();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	private static void normalTryException() throws Exception {
		MyResource mr = null;
		try {
			mr = new MyResource();
			System.out.println("MyResource created in the try block");
			if (true)
				throw new Exception("Exception in try");
		} finally {
			if (mr != null)
				mr.close();
		}

	}

	private static void tryWithResourceException() throws Exception {
		try (MyResource mr = new MyResource()) {
			System.out.println("MyResource created in try-with-resources");
			if (true)
				throw new Exception("Exception in try");
		}
	}

	static class MyResource implements AutoCloseable {

		@Override
		public void close() throws Exception {
			System.out.println("Closing MyResource");
			throw new Exception("Exception in Closing");
		}

	}
}

The output of the above program is:


MyResource created in try-with-resources
Closing MyResource
Exception in try
MyResource created in the try block
Closing MyResource
Exception in Closing

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

Comments

  1. Vimal Panchal says:

    Absolutely nice article.. Thanks for sharing it

  2. Manimegalai V says:

    This article clearly explain about the try with resourses statement.I gained more knowledge about java from this article.

  3. name says:

    Thanks for this post

  4. Jyotsana says:

    Another important point to not is that resource “declared” within a try-with-resource block is implicitly final.
    Compiler is responsilble to close this resource so it doesnt allow us to modify or re-assign this resource, because how will it find it later, at the time of closing?
    so, if we try to re-assign, compiler error saying “The resource a of a try-with-resources statement cannot be assigned”

  5. phani says:

    So the whole point in try-with-resources come into effect when the autocloseable interface is implemented or the call to close method is implemented?

  6. Amrita says:

    Hi All,
    I have one one doubt in the implementation of try-with-resources. Recently I used try-with-resources for a method which gives me JDBC connection in return as:
    public Connection getConnection() throws ClassNotFoundException, SQLException {
    try (Connection con = DriverManager.getConnection(dbUrl, naDBUser, naDBPass)) {
    con.setAutoCommit(false);
    return con;
    }
    }
    But the above implementation didnt work, as it seems that it returned the NULL connection object after closing the connection.On removing try-with-resources its working fine.
    So, can someone please suggest if there is a way to implement it with try-with-resources or try-finally block?

    1. Patan says:

      You cannot return the connection reference that is being closed by the try-with resource facility. You have to use the normal try-block to return the connection object.

  7. Arijit says:

    Regarding to // resources are closed as soon as try-catch block is executed said above. The Oracle website says, In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed

  8. Israel Tamariz says:

    Hi Pankash, also I think you can update the article using the Path interface from Java 8 NIO: https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html

    It also needs to be used with Try with Resources ….

    Very nice compilation of this topic, thanks.

  9. chandi says:

    Hi Pankaj
    I read your articles regularly , they are very informative and crisp . There is a wrong statement in the blog , that AutoCloseable extends Closeable , But the correct statement is Closeable Extends AutoCloseable.
    thanks
    chandi

    1. Pankaj says:

      Thanks for noticing the error and pointing it out. I have corrected the post.

  10. Arun says:

    HI Pankaj,

    I am regularly reading your articles and I have gained a lot of knowledge from this site. Thanks. In this article it is mentioned that
    Java 7 has introduced a new interface java.lang.AutoCloseable that extends java.io.Closeable interface. To use any resource in try-with-resources,

    but Closeable interface extends AutoCloseable interface right. Please correct me if I am wrong.

    Regards
    Arun

  11. thanu says:

    Java is excellent programming language.we also provide the training with more job opportunities.it is used to get better knowledge about the java.

  12. Advanced java Training says:

    try-with-resources not applicable to variable type

    for example

    try ( int y = a / b;)

    1. Preeti Garg says:

      Because int doesnot implement Java.lang.AutoCloseable Interface.

  13. Rohit says:

    ARM Blocks are I guess most useful feature of Java 7 along with String in Switch. These helps to perform daily programming activity with ease.

  14. Ralph says:

    Thanks for the information. One thing worth mentioning is that try() only closes resources on objects if their variable declaration is located in the try (….) statement.

    The following code does not call close of object B because there is no variable declaration for B.

    public class T {
    public static void main(String[] args) throws Exception {
    try (A a = new A(new B())) {
    System.out.println(“inside arm block”);
    }
    }
    private static class A implements AutoCloseable {
    public A(B b) {}
    public void close() throws Exception {
    System.out.println(“running A.close()”);
    }
    }

    private static class B implements AutoCloseable {
    public void close() throws Exception {
    System.out.println(“running B.close()”);
    }
    }
    }

    But it calls B.close if the ARM block looks like this:
    try (B b = new B(); A a = new A(b)) {

    }

    1. Pankaj says:

      Thats a great point to note Ralph, thanks for the code to understand this.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages