Try with Resource Statement

JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management. It is also referred to as automatic resource management.

Syntax

try(resource-specification(there can be more than one resource))
{
//use the resource
}catch()
{...}

This try statement contains a parenthesis in which one or more resources is declared. Any object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a parameter to try statement. A resource is an object that is used in program and must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement of the try block. You do not have to explicitly close the resources.


Example without using try with Resource Statement

import java.io.*;
class Test
{
public static void main(String[] args)
{
try{
String str;
//opening file in read mode using BufferedReader stream
BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));
while((str=br.readLine())!=null)
 {
System.out.println(str);
 }
br.close();	//closing BufferedReader stream
}catch(IOException ie)
{  System.out.println("exception");  }
 }
}

Example using try with Resource Statement

import java.io.*;
class Test
{
public static void main(String[] args)
{
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{
String str;
while((str=br.readLine())!=null)
{
System.out.println(str);
}
}catch(IOException ie)
{  System.out.println("exception");  }
}
}

NOTE: In the above example, we do not need to explicitly call close() method to close BufferedReader stream.


Points to Remember

  1. A resource is an object in a program that must be closed after the program has finished.
  2. Any object that implements java.lang.AutoCloseable or java.io.Closeable can be passed as a parameter to try statement.
  3. All the resources declared in the try-with-resources statement will be closed automatically when the try block exits. There is no need to close it explicitly.
  4. We can write more than one resources in the try statement.
  5. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.