try-with-resources Statement



The try-with-resources statement, introduced in Java 7, eliminates the need for a lengthy finally block.

  • Any class that implements the java.lang.AutoCloseable can be used as a resource.
  • If a resource must be autoclosed, its reference must be declared within the try statement's parentheses.
  • Resources opened using the try-with-resources statement are always closed.
  • Multiple resources can be opened by separating them with semicolons.
  • If multiple resources are opened, they will be closed in the opposite order in which they were opened.

try(resource_name) { //Statements }catch(Exception e) { //Statements }



A resource is an object that must be closed once your program is done using it, like a File resource or JDBC resource for 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.


Java 6

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

Java 7

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


try with resources advantages

  • More readable code and easy to write.
  • Automatic resource management.
  • Number of lines of code is reduced.
  • No need of finally block just to close the resources.
  • We can open multiple resources in try-with-resources statement separated by a semicolon.


Example Java 6

String readFirstLine(String path) throws IOException 
{
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
      }
 finally 
      {
   if (br != null)
    br.close();
      }
 }
 
 

Example Java 7


String readFirstLine(String path) throws IOException
 {
  try (BufferedReader br = new BufferedReader(new FileReader(path)))
	 {
  	 return br.readLine();
  	 }
 }
 

All resource will be freed automatically.


Points to remember

  • A resource must be declared in parenthesis, immediately after try block.
  • A Try-with-Resource can have catch and finally blocks, just as with try block.
  • There can be multiple resources in a single Try-with-Resource block.


Example 1: try-with-resources statement:


public void readEmployees(Connection con) { String sql = "Select * from Employee"; try ( Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql) ) { //Work with Statement and ResultSet } catch (SQLException e) { e.printStackTrace(); } }


In case of multiple resources, close() method of all the resources is called, and order of calling close() method is reverse of declaration.

Example 2: try-with-resources statement:


System.out.println("About to open a file");
try (
    InputStream in =
    new FileInputStream("missingfile.txt")
    ) 

{
System.out.println("File open");
int data = in.read();
}
catch (FileNotFoundException e) 
{
System.out.println(e.getMessage());
}
catch (IOException e) 
{
System.out.println(e.getMessage());
}


Resource in a try-with-resources statement must implement either:

  • The java.lang.AutoCloseable interface
  • The java.io.Closeable interface that extends the AutoCloseable interface.

The following code shows how to declare the AutoClosable interface with the close() method:

public interface AutoCloseable 
{
void close() throws Exception;
}