Try-with-resources: Auto-Cleanup

Try-with-resources: Auto-Cleanup in Java: To enter a semiconductor cleanroom you pass through a gowning airlock, and you leave the same way.

The Analogy: The Gowning Airlock At A Cleanroom Fab

To enter a semiconductor cleanroom you pass through a gowning airlock, and you leave the same way. On the way in you don garments in a fixed order: coverall first, then the hood, then boots, then the outer gloves. Each layer is logged as you put it on. On the way out, an automated de-gowning station takes each layer off for you in the exact reverse order -- gloves first, coverall last -- and it does this the moment you step into the exit lock, whether your shift ended normally or an alarm pulled you out early. You never have to remember to de-gown; the airlock guarantees it. Try-with-resources is that airlock. You declare your resources in the try (...) clause, use them in the block, and Java calls close() on every one of them automatically as you leave the block -- in reverse order of declaration, on every exit path.

The guarantee is the whole point. In the old world you gowned up, did your work, and were trusted to de-gown yourself in a finally step. If the work went badly and you rushed out, or if taking off one layer snagged and you gave up, layers were left on -- a contamination leak. Resources behaved the same: a file or connection opened in a try and closed by hand in finally leaked whenever someone forgot the finally, nested the close() wrong, or let the close throw and abandoned the rest. Try-with-resources removes the trust: the airlock de-gowns you, so the leak cannot happen through forgetfulness.

The reverse order matters as much as the guarantee. You cannot take the coverall off before the gloves without contaminating your hands, so the last layer donned is the first removed. Java closes resources in strictly reverse order of declaration for exactly this reason: a writer wrapped around a stream must be flushed and closed before the stream underneath it, or the buffered bytes are lost. Declaring the outer resource last means it closes first, and the dependency is respected automatically. See [[buffer-reader]] for where this layering shows up in practice.

The failure mode is subtle and it is about what happens when de-gowning itself goes wrong. Suppose the alarm sounded because of a real incident -- that is your primary problem -- and then, on the way out, a de-gowning fixture jams. A badly designed airlock would raise the jam as the headline and quietly forget why you were evacuating, so the incident report reads "glove fixture stuck" and the actual emergency vanishes. The old hand-written finally had exactly this bug: if the try block threw and then close() in finally also threw, the close exception replaced the original and the real fault was lost forever. Try-with-resources fixes this by keeping the original as the primary exception and attaching the close failure as a suppressed exception, so the real problem stays the headline and the secondary jam is still recorded.


Syntax or Core Structure

public class Fab {

    static class Gown implements AutoCloseable {
        private final String layer;
        Gown(String layer) {
            this.layer = layer;
            System.out.println("don:      " + layer);
        }
        void work() {
            System.out.println("work:     " + layer);
        }
        public void close() {
            System.out.println("doff:     " + layer);
        }
    }

    public static void main(String[] args) {
        try (Gown g = new Gown("coverall")) {
            g.work();
        }
        System.out.println("after:    block done");
    }
}

Output:

don:      coverall
work:     coverall
doff:     coverall
after:    block done

The Gown implements AutoCloseable, so declaring it in the try (...) clause enrols it in the airlock. Java calls close() -- printing doff -- automatically when the block ends, before the after line runs, with no finally written by hand.


Technical Depth: The Two Interfaces, Reverse-Order Closing, And Suppressed Exceptions

AutoCloseable Versus Closeable

Only objects whose type implements AutoCloseable can go in the try (...) clause. Closeable, the older interface from the IO library, extends AutoCloseable, so every Closeable also qualifies -- but the two differ in ways worth knowing.

Interfaceclose() throwsIntroducedIdempotent close required
AutoCloseableExceptionJava 7Not required, but recommended
CloseableIOExceptionJava 5Yes, must be idempotent

AutoCloseable is the general contract; its close() may throw any Exception. Closeable narrows that to IOException and additionally promises that calling close() more than once has no effect. When you write a custom resource, implement AutoCloseable unless you are specifically modelling an IO stream, and keep close() idempotent regardless.

Closing Happens In Reverse Order

When several resources are declared in one try clause, they close in strictly reverse order -- last declared, first closed -- which is what lets an outer wrapper release before the inner thing it depends on.

public class Layers {

    static class Layer implements AutoCloseable {
        private final String id;
        Layer(String id) {
            this.id = id;
            System.out.println("open:     " + id);
        }
        public void close() {
            System.out.println("close:    " + id);
        }
    }

    public static void main(String[] args) {
        try (Layer coverall = new Layer("coverall");
             Layer gloves   = new Layer("gloves")) {
            System.out.println("body:     working");
        }
    }
}

Output:

open:     coverall
open:     gloves
body:     working
close:    gloves
close:    coverall

coverall is declared first and gloves second, so they open in that order; on exit gloves closes first and coverall last. Declare the resource that others depend on first, so it is torn down last.

Suppressed Exceptions: Keeping The Real Fault

The subtle case is when the block throws and close() throws. The two approaches diverge sharply on what a caller ends up seeing.

ScenarioHand-written finally that rethrowsTry-with-resources
Only the body throwsBody exception propagatesBody exception propagates
Only close() throwsClose exception propagatesClose exception propagates
Both throwClose exception replaces body -- body lostBody is primary, close is suppressed

Try-with-resources keeps the block's exception as primary and attaches the close failure as a suppressed exception, reachable through getSuppressed().

public class Suppressing {

    static class Faulty implements AutoCloseable {
        public void close() throws Exception {
            throw new Exception("close failed");
        }
    }

    public static void main(String[] args) {
        try (Faulty f = new Faulty()) {
            throw new RuntimeException("body failed");
        } catch (Exception e) {
            System.out.println("primary:    " + e.getMessage());
            Throwable[] s = e.getSuppressed();
            System.out.println("suppressed: " + s.length);
            if (s.length > 0) {
                System.out.println("first:      " + s[0].getMessage());
            }
        }
    }
}

Output:

primary:    body failed
suppressed: 1
first:      close failed

The body's RuntimeException is the primary exception a caller sees; the close() failure is not lost but demoted to a suppressed exception on it. A hand-written finally that rethrew from close() would have done the opposite -- lost the body failure and surfaced only the close failure, which the next section shows.


Real World Example: The Masking Bug That Try-with-resources Fixes

Here is the exact fault the analogy warned about. Design A closes by hand in a finally and rethrows if the close fails; Design B uses try-with-resources. Both wrap a sensor whose read() fails and whose close() fails -- the realistic bad-day scenario.

public class Cleanup {

    static class Sensor implements AutoCloseable {
        void read() { throw new RuntimeException("read failed"); }
        public void close() throws Exception {
            throw new Exception("close failed");
        }
    }

    // Design A: hand-written finally. Rethrowing from close REPLACES the read failure.
    static String manual() {
        Sensor s = new Sensor();
        try {
            s.read();
            return "ok";
        } finally {
            try {
                s.close();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    // Design B: try-with-resources. The read failure stays primary.
    static String modern() throws Exception {
        try (Sensor s = new Sensor()) {
            s.read();
            return "ok";
        }
    }

    public static void main(String[] args) {
        try {
            manual();
        } catch (RuntimeException e) {
            System.out.println("A primary:    " + e.getMessage());
        }
        try {
            modern();
        } catch (Exception e) {
            System.out.println("B primary:    " + e.getMessage());
            Throwable[] sup = e.getSuppressed();
            System.out.println("B suppressed: " + sup.length);
            if (sup.length > 0) {
                System.out.println("B first:      " + sup[0].getMessage());
            }
        }
    }
}

Output:

A primary:    close failed
B primary:    read failed
B suppressed: 1
B first:      close failed

The difference is stark and it is a real bug, not a stylistic preference. In Design A the diagnostic that reaches whoever is on call is "close failed" -- the sensor's read failure, the thing that actually broke the operation, has been overwritten by the cleanup failure and is gone. An engineer paged at 3am chases a red herring about resource closing while the real read failed fault is invisible. This is the masking bug: a finally that can throw silently destroys the original exception whenever both fail.

Design B keeps the truth. The read failure is the primary exception, so the headline is read failed -- the real problem -- and the close failure is preserved as a suppressed exception, still there in getSuppressed() for anyone who wants the full picture. Nothing is lost and nothing is misranked. The airlock recorded the emergency as the emergency and the jammed fixture as a footnote, which is exactly the ordering a debugger needs.

The mechanism composes cleanly with the rest of exception handling. The primary exception propagates and can be caught by type as usual, matched against the hierarchy from [[custom-exceptions]]; the suppressed list rides along attached to it. Contrast this with the manual [[finally-block]] approach, where getting suppression right by hand means catching the close exception, calling addSuppressed on a variable holding the primary, and rethrowing -- boilerplate almost nobody writes correctly, which is the whole reason the language feature exists.

It is not a cure-all, and the honest limits are worth stating. Try-with-resources only manages resources declared in its own try clause, so a resource opened earlier and merely used inside still needs manual handling. Suppressed exceptions are genuinely easy to miss: a catch block that logs only getMessage() throws the suppressed list away, so the close failure that Design B carefully preserved can still be lost downstream by a careless handler. And there is a real design flaw to watch for in custom resources -- a close() that does meaningful work such as flushing a buffer can fail in a way that loses data, and demoting that to a suppressed exception makes it easy to overlook exactly when it matters most. The feature guarantees close() is called; it cannot guarantee the close succeeds, and a resource whose close can silently drop data needs its own explicit check.


Common Mistakes

  1. Declaring the resource outside the try clause. Writing Scanner s = new Scanner(...); and then try (s) { ... } works only for an effectively-final variable and misses the point when people instead open it and never enrol it at all. Declare the resource inside try (...) so the airlock actually manages it.
  1. Still closing by hand in a finally. Adding a finally { s.close(); } after a try-with-resources closes the resource twice. It is redundant at best and, for a non-idempotent close(), a bug. Let the construct own the closing entirely.
  1. Assuming close() never throws. A buffered writer's close() flushes and can fail. Treating close as guaranteed-silent means a flush failure -- and the data loss behind it -- passes unnoticed. Account for the fact that close() can throw.
  1. Logging only getMessage() and dropping the suppressed list. A catch that prints e.getMessage() and nothing else discards everything in getSuppressed(), throwing away the very close failures the construct preserved. Log the suppressed exceptions too.
  1. Using a type that is not AutoCloseable. Putting an object whose class does not implement AutoCloseable in the try (...) clause does not compile. The clause is restricted to resources; a plain object cannot be enrolled.
  1. Declaring resources in the wrong order. Declaring the underlying stream last means it closes first, before the writer wrapped around it has flushed -- losing buffered bytes. Declare the dependency first so it closes last.
  1. Making close() non-idempotent. A close() that misbehaves or throws on a second call turns any accidental double-close into a fault. Write close() so calling it twice is harmless, matching the Closeable contract.
  1. Doing heavy work in close(). A close() that runs a long operation or blocks on IO turns every block exit into a latency spike and every failure into a lost cause. Keep close() fast and focused on release.
  1. Expecting the block's return value after a close failure. If close() throws on the way out, the try block's would-be return never surfaces -- the close exception propagates instead (as primary only when the body did not itself throw). Do not rely on a return value escaping a failing close.

Best Practices

  • Always declare resources inside the try (...) clause. Enrol every closable resource in the construct rather than opening it separately, so the automatic close is guaranteed on every exit path.
  • Give each resource its own line. Declaring one resource per line, separated by semicolons, makes the reverse-close order obvious and keeps the dependency direction readable.
  • Prefer try-with-resources over a hand-written finally. For anything AutoCloseable, let the construct close it. The manual [[finally-block]] approach is where the masking bug and the leaks live.
  • Make custom close() idempotent and cheap. Writing close() so a second call is harmless, and keeping it fast, means accidental double-closes and block exits never turn into faults or latency.
  • Implement AutoCloseable for custom resources. Choose AutoCloseable unless you are specifically modelling an IO stream that warrants Closeable; it is the general contract and its close() can throw a broad Exception.
  • Log suppressed exceptions. In any catch around a resource block, walk getSuppressed() as well as the primary, so close failures that the construct preserved are actually recorded.
  • Declare dependencies before dependents. Put the resource others rely on first in the clause, so it closes last -- after the wrappers that need it have flushed and released.
  • Do not double-close. Trust the construct to close what it declared, and avoid adding manual close() calls that would run a second time.

Practice Exercises

  1. The auto-closing resource. Write a custom class Machine that implements AutoCloseable, prints a start message in its constructor and a stop message in close(), and has a run() method. Use it in a try-with-resources block and confirm from the output that close() runs automatically after the block, without any finally.
  1. Reverse-order proof. Declare two AutoCloseable resources, outer and inner, in a single try clause, each printing its id on open and on close. From the output, confirm they open in declaration order and close in reverse -- inner before outer if inner is declared second.
  1. Preserve the primary fault. Write a resource whose close() throws, use it in a try-with-resources block that also throws from the body, and in the catch print the primary exception's message, the length of getSuppressed(), and the suppressed exception's message. Confirm the body failure is primary and the close failure is suppressed.