As the try-catch-final statement example illustrates, resource cleanup using a finally clause requires a significant amount of “boiler-plate” code to implement the edge-cases correctly. Java 7 provides a much simpler way to deal with this problem in the form of the try-with-resources statement.

What is a resource?

Java 7 introduced the java.lang.AutoCloseable interface to allow classes to be managed using the try-with-resources statement. Instances of classes that implement AutoCloseable are referred to as resources. These typically need to be disposed of in a timely fashion rather than relying on the garbage collector to dispose of them.

The AutoCloseable interface defines a single method:

public void close() throws Exception

A close() method should dispose of the resource in an appropriate fashion. The specification states that it should be safe to call the method on a resource that has already been disposed of. In addition, classes that implement Autocloseable are strongly encouraged to declare the close() method to throw a more specific exception than Exception, or no exception at all.

A wide range of standard Java classes and interfaces implement AutoCloseable. These include:

Application and third party classes may do this as well.

The basic try-with-resource statement

The syntax of a try-with-resources is based on classical try-catch, try-finally and try-catch-finally forms. Here is an example of a “basic” form; i.e. the form without a catch or finally.

try (PrintStream stream = new PrintStream("hello.txt")) {
    stream.println("Hello world!");
}

The resources to be manage are declared as variables in the (...) section after the try clause. In the example above, we declare a resource variable stream and initialize it to a newly created PrintStream.

Once the resource variables have been initialized, the try block is executed. When that completes, stream.close() will be called automatically to ensure that the resource does not leak. Note that the close() call happens no matter how the block completes.

The enhanced try-with-resource statements

The try-with-resources statement can be enhanced with catch and finally blocks, as with the pre-Java 7 try-catch-finally syntax. The following code snippet adds a catch block to our previous one to deal with the FileNotFoundException that the PrintStream constructor can throw: