Monday, May 23, 2011

new try-catch in java

As we have experienced this, it is difficult to correctly close resources. For example, if you open a file or a socket, it is easy to forget to close it. Your code can easily ran out of file handles if not properly taken care of.
To make things easier, Java 7 introduced the new "try with resources" syntax. It automatically closes any AutoCloseable resources referenced in the try statement. For example, instead of manually closing streams ourselves, we can simply do this:

import java.io.*;

public class AutomaticResourceClosing {
  public static void main(String[] args) throws IOException {
    try (
      PrintStream out = new PrintStream (
          new BufferedOutputStream(
              new FileOutputStream("foo.txt")))
    ) {
      out.print("Unable to close resource");
    }
  }
}


Take note that there is never a semicolon at the end of the "try ()" declaration.

You can read more about other features by going to Java.net site ( http://jdk7.java.net/ ).