try-with-resources and cleanup

AutoCloseable, suppressed exceptions, finally's foot-guns, and the resource leak that shows up as a connection pool exhausted at 3am.

7 min read🧰 Exceptions, I/O and Reflection

A resource is anything you must give back: a file handle, a socket, a database connection, a lock. Forgetting to give it back is a leak, and a leak in a server is not a crash — it is a service that works for three days and then stops accepting connections. try-with-resources is the mechanism that makes giving back automatic, and it has two subtleties that the finally block it replaced could never get right.

The old way and why it was wrong

java
InputStream in = null;
try {
    in = Files.newInputStream(path);
    process(in);
} finally {
    if (in != null) in.close();       // if close() throws, the original exception is lost
}

Three problems. It is verbose. If process throws and close throws, the exception from close replaces the one from process, and you debug the wrong failure. And with two resources, the nesting doubles.

try-with-resources

java
try (InputStream in = Files.newInputStream(path);
     BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8))) {
    return reader.lines().count();
}

Anything that implements AutoCloseable can be declared in the parentheses. The compiler generates the close calls — in reverse order of declaration, so reader closes before in — whether the block completes, returns, or throws. Since Java 9 an effectively-final variable declared earlier can be used: try (in) { ... }.

Suppressed exceptions

If the body throws and a close() also throws, the body's exception is the one propagated, and the close() exception is attached to it as suppressed:

java
try (var r = new Resource()) {
    throw new IllegalStateException("body failed");
}
// caught: IllegalStateException: body failed
//   Suppressed: java.io.IOException: close failed

e.getSuppressed() returns them; stack traces print them. The primary failure is preserved, and the secondary one is not lost. This is the behaviour the manual finally could not produce.

finally's remaining uses and its foot-guns

finally still exists for cleanup that is not a resource — resetting a flag, restoring a thread's context class loader, releasing a lock acquired with lock() (which is not AutoCloseable). Two things to never do in it:

  • return in finally. It discards any exception thrown in the body, silently. Same for break and continue.
  • Throwing from finally. It replaces the in-flight exception, the same loss try-with-resources was designed to prevent.
java
lock.lock();
try {
    mutate();
} finally {
    lock.unlock();      // correct: the one thing finally is still for
}

Implementing AutoCloseable

Your own classes that own resources should implement it, so callers can use them in try:

java
public final class BatchWriter implements AutoCloseable {
    private final Connection conn;
    private boolean closed;
 
    @Override public void close() {
        if (closed) return;             // idempotent: closing twice is harmless
        closed = true;
        conn.close();
    }
}

close() should be idempotent, should release everything even if one release fails (catch, add as suppressed, continue), and should not throw a checked exception unless it genuinely must — AutoCloseable.close() declares throws Exception, but you can narrow it to nothing, which spares every caller a catch.

The leak that shows up at 3am

java
public List<Order> load(long customerId) {
    Connection c = dataSource.getConnection();               // borrowed from the pool
    PreparedStatement ps = c.prepareStatement(SQL);
    ps.setLong(1, customerId);
    ResultSet rs = ps.executeQuery();                          // throws on a bad row
    ...
    c.close();                                                // never reached on the throw
}

One bad row means one connection never returned. HikariCP's default pool is ten. Ten bad rows over a day and every request waits thirty seconds for a connection that will never come, then fails with SQLTransientConnectionException: connection is not available. The service is up; every endpoint that touches the database is down. This is the single most common resource leak in Java services, and the fix is the three-resource try you would write on the first day of a Java course.

Streams that are resources

Files.lines(path), Files.list(dir), Files.walk return streams that hold an open handle. Close them: try (Stream<String> lines = Files.lines(path)) { ... }. A stream from a collection does not need this; a stream from the file system does.

Under the hood: how the compiler desugars try-with-resources

try-with-resources is not a JVM feature — there is no bytecode instruction for it. The compiler rewrites it into an ordinary try/catch/finally, and the JLS spells out exactly what that rewrite looks like (§14.20.3). For one resource, a try (Identifier = Expression) { Block } becomes, in effect:

java
{
    final var resource = Expression;
    Throwable primaryExc = null;
    try {
        Block
    } catch (Throwable t) {
        primaryExc = t;
        throw t;
    } finally {
        if (resource != null) {
            if (primaryExc != null) {
                try {
                    resource.close();
                } catch (Throwable suppressedExc) {
                    primaryExc.addSuppressed(suppressedExc);
                }
            } else {
                resource.close();
            }
        }
    }
}

Two things this makes precise that the earlier sections only asserted. First, addSuppressed is called only inside the primaryExc != null branch — suppression exists because there is already a primary exception in flight when close() runs, not as a general property of the resource closing. Second, look at the else: when the body completes normally, close() is called with no surrounding catch. If it throws there, that exception is not suppressed by anything — it simply propagates as the exception, because there was no primary failure for it to attach to. A close() that fails after a perfectly successful body looks, from the catch block's point of view, exactly like the body itself failed.

For more than one resource, the JLS's "extended" form (§14.20.3.2) nests one basic try-with-resources inside another, resource by resource, in declaration order — which is the actual mechanism behind "closes in reverse order": the innermost try (the last-declared resource) closes first as its own finally runs, then control returns to the next finally out, which closes the resource declared before it.

Try it yourself

java
class Boom implements AutoCloseable {
    public void close() { throw new IllegalStateException("close failed"); }
}
try {
    try (Boom b = new Boom()) {
        throw new RuntimeException("body failed");
    }
} catch (RuntimeException e) {
    System.out.println(e.getMessage());
    for (Throwable s : e.getSuppressed()) System.out.println("suppressed: " + s.getMessage());
}

Predict before running: what if the body doesn't throw?

Using the desugaring above, work out: if Boom's body ran System.out.println("ok"); instead of throwing, and close() still threw IllegalStateException, would the catch block above ever see that exception as suppressed?

No — it becomes the primary exception, because there is no other one

Trace it through the rewrite: the body completes normally, so primaryExc stays null, and the finally block takes the else branch — a bare resource.close() with no surrounding try/catch. When that close() throws IllegalStateException, nothing catches it inside the finally, so it propagates out of the whole try-with-resources statement as the one and only exception the caller sees. getSuppressed() on it returns an empty array — there was never a primary exception for anything to be suppressed under. This is the case the lesson's earlier "Suppressed exceptions" section does not cover, because that section only walks through body-fails-and-close-fails; body-succeeds-and-close-fails is a different branch of the same desugared code, with a different, simpler outcome.

Misconceptions

  • "A close() failure after a successful body still shows up as suppressed." It does not — suppression only happens in the branch where a primary exception already exists. A close()-only failure propagates as the primary exception itself, with nothing suppressed under it (see the exercise above).
  • "A finally block written around the whole try-with-resources runs before the resource closes." It runs after. The compiler's own finally — the one in the desugaring, which calls close() — is inside the statement; any finally you write yourself wraps the entire already-desugared block, so it always executes once the resource is already closed (or has already failed to close).

Sources

  • The Java Language Specification, SE 21 — §14.20.3 (The try-with-resources Statement), the basic and extended desugaring.
  • java.lang.AutoCloseable and java.lang.Throwable#addSuppressed/getSuppressed Javadoc.
  • Joshua Bloch, Effective Java, 3rd ed. — Item 9, "Prefer try-with-resources to try-finally".
Progress is saved on this device and to your account when signed in.