try-with-resources & AutoCloseable
Guaranteed resource cleanup, reverse close order, and suppressed exceptions.
Automatic resource cleanup
Before Java 7, releasing resources (files, connections, streams) required fragile nested try/finally blocks. try-with-resources guarantees close() is called automatically:
try (var reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} // reader.close() is called here, even if an exception is thrown
Any class that implements AutoCloseable (or its sub-interface Closeable) can be declared in the resource list.
Multiple resources — reverse-close order: resources are closed in reverse order of declaration:
try (var conn = openConnection(); // opened first, closed LAST
var stmt = conn.createStatement(); // opened second, closed FIRST
var rs = stmt.executeQuery("...")) { // opened third, closed FIRST of all — wait:
// close order: rs first, then stmt, then conn
}
The close order is: last declared → first closed.
Suppressed exceptions: if the try body throws AND close() also throws, Java preserves both. The close() exception is suppressed — attached to the primary exception:
try {
primary.cause();
} catch (Exception e) {
Throwable[] suppressed = e.getSuppressed(); // the close() exception
}
Contrast with the old try/finally: if both the try body and finally throw, the finally exception replaces the original — the first exception is silently lost. try-with-resources fixes this.