Prefer try-with-resources over try-finally

The try-finally construction in Java is often used to close the resources. Finally block will be always executed, so no matter what has happened in the ‘try’ block, the file or connection will always be closed. However, since Java7, there is an easier and more succinct way to do it – try-with-resources.

Not only does it look better and gets rid of the boiler plate code, it also behaves better. When we use try-with-resources, the exception thrown in the ‘try’ block, will suppress the one (possibly) thrown  in the ‘finally’ block. If we use the standard try-finally, the latter exception is the one that surfaces in the stack trace, which is usually not the one we are worried about.

Here is a sample for try-with-resources statement:

public class HeavyLineCopier {
    public static void copy(String src, String dst) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(src));
             BufferedWriter bw = Files.newBufferedWriter(Paths.get(dst), StandardCharsets.US_ASCII)) {
            bw.write(br.readLine());
        } finally {
            System.out.println("All closed!");
        }
    }
}

How does try with resources work? It automatically closes the resources declared in the initial parentheses, in reverse order, that they were opened.

Why does it work? It uses AutoClosable interface method close(). No magic here, any class can implement this interface and be the subject to try-with-resources statement.

Oracle documentation on try-with-resources:

This post is based on Joshua Bloch Effective Java Third Edition (get it on Amazon: https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997).