try-with-resources

Automatic Closing

Files, database connections and sockets must be closed. try-with-resources (Java 7+) closes any object that implements AutoCloseable automatically, even when an exception happens. Resources close in reverse order of opening.

Example

public class Main {
    public static void main(String[] args) {
        try (Resource db = new Resource("DB connection");
             Resource file = new Resource("Log file")) {
            System.out.println("Working with resources");
            throw new IllegalStateException("query failed");
        } catch (IllegalStateException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}

class Resource implements AutoCloseable {
    private final String name;

    Resource(String name) {
        this.name = name;
        System.out.println("Open  " + name);
    }

    @Override
    public void close() {
        System.out.println("Close " + name);
    }
}

Output

Open  DB connection
Open  Log file
Working with resources
Close Log file
Close DB connection
Caught: query failed

Note: Notice that both resources are closed before the catch block runs.

Before and After

// Before Java 7: verbose and easy to get wrong
BufferedReader reader = null;
try {
    reader = Files.newBufferedReader(path);
    System.out.println(reader.readLine());
} finally {
    if (reader != null) {
        reader.close();
    }
}

// Java 7+: try-with-resources
try (BufferedReader r = Files.newBufferedReader(path)) {
    System.out.println(r.readLine());
}