Code Snippets
/

try-with-resources Pattern

try-with-resources Pattern

`try-with-resources` (Java 7+) automatically closes any object that implements `AutoCloseable` when the block exits, normally or via exception. This snippet covers the basic form, declaring multiple resources, the Java 9 enhancement that lets you reuse an existing variable, and writing your own `AutoCloseable` to participate in the pattern. Use it for every reader, writer, stream, lock, and database connection you open.

Java
Medium
3 snippets
java-exception-handling
error-handling
java-file-io

1,126 views

26

import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class Main {
    public static void main(String[] args) throws IOException {
        // BufferedReader is AutoCloseable; the try block guarantees close().
        try (BufferedReader br = new BufferedReader(new StringReader("hello\nworld"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("line: " + line);
            }
        } // close() runs here, even if readLine() threw.
    }
}

The resource is declared inside the try (...) parentheses; when control leaves the block (normal exit, return, or exception) the runtime calls close() automatically. Compare this with the pre-Java-7 idiom of a try / finally that had to null-check and re-catch close exceptions: a 15-line dance shrinks to four lines. The compiler also wires up suppressed exceptions correctly, so a primary failure inside the block is not lost when close() itself throws.