Way2Java

Try with Resources Example

Every version of Java adds some new features and the latest version JDK 1.7 (as on August, 2013) comes with new additions.

Following are the new additions.

1. String in Switch Expression
2. Underscores Between Digits in Numeric Literals
3. Integral Types as Binary Literals
4. Handling multiple exceptions in a single catch block
5. Try-with-resources Statement
6. Automatic Type Inference in Generic object instantiation

Now let us discuss Try with Resources Example Statement

With JDK 1.7, no finally block is required to close (with close() methods) the resources of files or sockets or JDBC handles (objects) etc. The resources (say objects) opened in try block automatically close when the execution control passes out try block (say, at the close brace of try block).

Your Earlier code before Java 7:

import java.io.*;
public class Demo
{
  public static void main(String args[])
  {
    FileReader fr = null;
    FileWriter fw = null;
    try
    {
      fr = new FileReader("abc.txt");
      fw = new FileWriter("def.txt");

      // some file copying code
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
    finally
    {
      try
      {
        if(fr != null) fr.close();      //closing code here.  This is not necessary from JDK 1.7 with Try with Resources Example
        if(fw != null) fw.close();
      }
      catch(IOException e)
      { 
        e.printStackTrace();
      }
    }
   }
}

Your Present code with JDK 1.7:

import java.io.*;
public class Demo
{
  public static void main(String args[])
  {
    try ( 
          FileReader fr = new FileReader("abc.txt");   // Try with Resources Example, fr closes implicitly
          FileWriter fw = new FileWriter("def.txt");   // Try with Resources Example, fw closes implicitly
        )
        {
          // some file copying code
        }            // at this point fr and fw are closed
        catch (IOException e) 
        {
          e.printStackTrace();
        }
  }
}

A new interface AutoCloseable is introduced with JDK 1.7 for this purpose.

public interface java.lang.AutoCloseable 
{
  public abstract void close() throws java.lang.Exception;
}

Any resource (class) that implements interface "java.lang.AutoCloseable" is eligible as a resource statement to write in try block.

The close() method of AutoCloseable is called implicitly to close the handles. Observe, the close() method throws Exception which you may or may not catch if your code does not demand, or replace with problem specific exception class. In the above code, I used IOException. Note that close() method java.lang.Closeable interface is very different from this.

JDBC 4.1 can make use of this try-catch-resource management.

All the remaining features (including the present one) are discussed in JDK 1.7 Features.