Memra

try-with-resources & AutoCloseable

◈ 4 cards

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.

123456openconnstmtrsclosersstmtconnLast declared, first closed.
Reverse order is what keeps dependents safe: the ResultSet closes while its Statement is still open, and the Statement while its Connection is still open. Declaring them in the wrong order is the only way to break that.
when both throwyou catchthe other onetry / finallythe one from finallylost silentlytry-with-resourcesthe one from the bodygetSuppressed()
This is the real reason try-with-resources exists. In the old pattern a failure during cleanup erases the failure that caused it; try-with-resources keeps the original and files the other under getSuppressed().
NORMAL ~/memra/learn/java-from-zero/try-with-resources utf-8 LF