Java Snippet

try-with-resources Pattern

Difficulty: Medium

`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.

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,125 views

26

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.