Java 7 try-with-resources


I would like to celebrate today’s release of Java 7 with discussing one of the new features that I consider especially helpful: The try-with-resources Statement.

Apart from saving a lot of typing, this statements helps to avoid typical errors in dealing with resources that I have seen now in ~100 student assignments. Consider the following code:

//get some content to write to a file
String path = "myFile";
try {
  BufferedWriter buffer = new BufferedWriter(new FileWriter(path));
  buffer.write("...");
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if (buffer != null) {
    try {
      buffer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

The code in the finally block is necessary to properly close the writer (and thus release any system resources associated with it). However, in Java 6 no one forces you to properly close resources which is why most people new to the subject simply forget it. The try-with-resources statement in Java 7 takes away the burden of explicitly closing a resource. The adjusted syntax looks as follows:

//get some content to write to a file
String path = "myFile";
try (BufferedWriter buffer = new BufferedWriter(new FileWriter(path))){
  buffer.write("...");
} catch (IOException e) {
  e.printStackTrace();
}

The writer is closed properly and less code is needed. Any class that implements java.lang.AutoClosable (which includes all classes that implement java.io.Closable, as this interface extends AutoClosable), can be used in try-with-resources.

There is one not so intuitive issue with this statement, related to the suppression of exceptions. On execution of the above try-with-resources block, two exceptions might be thrown. One from the content of the try (buffer.write()) and another one from the -with-resources part (buffer.close()). Only one of these exceptions is propagated from the try and that is the one from its content (buffer.write()). The other one (buffer.close()) is suppressed, but still accessible via an extension of Throwable. This class now offers additional methods for setting and accessing suppressed exceptions (Throwable[] getSurpressed()).

Advertisements

2 thoughts on “Java 7 try-with-resources

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s