try-with-resources

try-with-resources closes files, sockets, streams and locks automatically, in the right order, even when exceptions are thrown, and it keeps the exception that matters. This page explains what the compiler turns the statement into, shows the closing order and how suppressed exceptions work, reproduces the two leaks it does not prevent, measures leaked file handles, and turns any cleanup into an AutoCloseable.

Contents

What try-with-resources does

A resource is an object that holds something outside the Java heap, such as an open file, a socket or a database connection, and must be released explicitly with close(). Before Java 7, releasing it correctly took a try/finally block per resource, and the obvious way to write it lost exceptions. The try-with-resources statement (Java 7, part of Project Coin) does it for you:

  • Every resource declared in the parentheses is closed when the block ends, whether it ends normally, by return, or by an exception.
  • Resources are closed in the reverse order of their declaration, so a resource that depends on another is closed first.
  • If the body throws and close() also throws, the body's exception is the one that propagates, and the exception from close() is attached to it as a suppressed exception instead of replacing it.
  • Any catch and finally clauses run after the resources have been closed.

The statement works with any object that implements java.lang.AutoCloseable, an interface with one method, void close() throws Exception. The JLS (section 14.20.3) defines it entirely as a translation into ordinary try, catch and finally, which the third program writes out by hand.

The pieces of try-with-resources
PieceSinceNotes
java.io.CloseableJava 5close() throws IOException; closing twice must have no effect
AutoCloseable and try-with-resourcesJava 7Closeable now extends it; close() may throw any exception
Throwable.addSuppressed, getSuppressedJava 7Where exceptions from close() end up
Existing effectively final variables as resources: try (r)Java 9No need to declare a new variable for a resource made earlier
ExecutorService and ForkJoinPool become AutoCloseableJava 19close() waits for submitted tasks

The examples ran on JDK 21. Each one is self-contained and uses small resource classes that print what happens to them.

Opening, using and closing

Two resources in one statement show the closing order; a failing body shows when catch and finally run; and the last two cases show the Java 9 form and a null resource.

Java
public class TwrBasics {

    // A resource that reports when it is opened, used and closed
    static class Resource implements AutoCloseable {
        private final String name;

        Resource(String name) {
            this.name = name;
            System.out.println("  open  " + name);
        }

        void use(boolean fail) {
            System.out.println("  use   " + name);
            if (fail) {
                throw new IllegalStateException("use of " + name + " failed");
            }
        }

        @Override
        public void close() {
            System.out.println("  close " + name);
        }
    }

    public static void main(String[] args) {
        System.out.println("two resources, normal run:");
        try (Resource db = new Resource("db");
             Resource file = new Resource("file")) {
            db.use(false);
            file.use(false);
        }

        System.out.println("an exception in the body, with catch and finally:");
        try (Resource db = new Resource("db")) {
            db.use(true);
        } catch (IllegalStateException e) {
            System.out.println("  catch:   " + e.getMessage() + " (close already ran)");
        } finally {
            System.out.println("  finally: runs last");
        }

        // Java 9: an effectively final variable declared earlier can be listed directly
        Resource existing = new Resource("existing");
        System.out.println("existing resource:");
        try (existing) {
            existing.use(false);
        }

        // A null resource is allowed: close() is simply not called
        System.out.println("null resource:");
        try (Resource none = null) {
            System.out.println("  body ran with none = " + none);
        }
    }
}

Output:

Output
two resources, normal run:
  open  db
  open  file
  use   db
  use   file
  close file
  close db
an exception in the body, with catch and finally:
  open  db
  use   db
  close db
  catch:   use of db failed (close already ran)
  finally: runs last
  open  existing
existing resource:
  use   existing
  close existing
null resource:
  body ran with none = null
  • The resources opened in declaration order, db then file, and closed in reverse, file then db. With a reader wrapped around a stream, the outer one is closed before the inner one, which is what both expect.
  • When the body threw, close ran first, then the catch block, then finally. By the time a catch block runs, the resource is already closed and cannot be used for clean-up work.
  • try (existing) closed a resource created before the statement. Since Java 9 the variable only has to be final or effectively final; it no longer needs to be declared inside the parentheses.
  • A resource that is null is allowed, and the generated code simply skips its close(). That keeps code like try (var in = optionalStreamOrNull()) free of null checks.

Suppressed exceptions

A resource whose use and close both throw is the case where the old pattern goes wrong. The program uses two such resources with try-with-resources, then the same failure with hand-written try/finally, and finally a body that succeeds while close fails.

Java
public class Suppressed {

    static class Flaky implements AutoCloseable {
        private final String name;

        Flaky(String name) {
            this.name = name;
        }

        void use() {
            throw new IllegalStateException("use of " + name + " failed");
        }

        @Override
        public void close() {
            throw new IllegalStateException("close of " + name + " failed");
        }
    }

    @SuppressWarnings("try")       // javac warns about resources the body never uses
    public static void main(String[] args) {
        // 1. Body and close() both throw: the body's exception wins, close's is attached
        try (Flaky a = new Flaky("a"); Flaky b = new Flaky("b")) {
            a.use();
        } catch (IllegalStateException e) {
            System.out.println("try-with-resources:");
            System.out.println("  primary:    " + e.getMessage());
            for (Throwable s : e.getSuppressed()) {
                System.out.println("  suppressed: " + s.getMessage());
            }
        }

        // 2. The old try/finally pattern: the exception from close() replaces the real one
        try {
            Flaky r = new Flaky("legacy");
            try {
                r.use();
            } finally {
                r.close();
            }
        } catch (IllegalStateException e) {
            System.out.println("try/finally:");
            System.out.println("  reported:   " + e.getMessage()
                    + " (suppressed: " + e.getSuppressed().length + ")");
        }

        // 3. Only close() throws: that exception becomes the primary one
        try (Flaky c = new Flaky("c")) {
            System.out.println("body of c finished normally");
        } catch (IllegalStateException e) {
            System.out.println("  primary:    " + e.getMessage());
        }
    }
}

Output:

Output
try-with-resources:
  primary:    use of a failed
  suppressed: close of b failed
  suppressed: close of a failed
try/finally:
  reported:   close of legacy failed (suppressed: 0)
body of c finished normally
  primary:    close of c failed
  • The primary exception is the body's "use of a failed". Both resources were still closed, b before a, and both of their failures were attached with addSuppressed, in that order. A stack trace prints them under "Suppressed:", so nothing is lost.
  • With try/finally, the exception thrown by close() in the finally block replaced the original one: the report says "close of legacy failed" and has no suppressed exceptions. The real cause, the failed use, is gone. Avoiding this is the main reason to prefer try-with-resources even for a single resource.
  • When only close() fails, its exception is the primary one. A write that is buffered and flushed only in close() fails exactly this way, so a successful body does not mean the data reached the disk.

The @SuppressWarnings("try") on main is there because javac -Xlint warns when a declared resource is never used inside the body; here that is deliberate.

What the compiler generates

The JLS specifies try-with-resources as a translation. The program writes that translation out by hand for one resource, with a body and a close() that both throw, and compares it with the real statement.

Java
public class Desugared {

    static class Res implements AutoCloseable {
        private final String name;

        Res(String name) {
            this.name = name;
        }

        @Override
        public void close() {
            System.out.println("  close " + name);
            throw new IllegalStateException("close " + name);
        }
    }

    static void body() {
        throw new IllegalArgumentException("body");
    }

    @SuppressWarnings("try")       // javac warns about resources the body never uses
    public static void main(String[] args) {
        // What the compiler writes for:  try (Res r = new Res("r")) { body(); }
        // (JLS 14.20.3.1, slightly simplified)
        try {
            final Res r = new Res("r");
            Throwable primary = null;
            try {
                body();
            } catch (Throwable t) {
                primary = t;
                throw t;
            } finally {
                if (r != null) {
                    if (primary != null) {
                        try {
                            r.close();
                        } catch (Throwable closeFailure) {
                            primary.addSuppressed(closeFailure);
                        }
                    } else {
                        r.close();
                    }
                }
            }
        } catch (RuntimeException e) {
            System.out.println("hand-written: " + e.getMessage() + ", suppressed "
                    + e.getSuppressed()[0].getMessage());
        }

        // The real statement gives the same result
        try (Res r = new Res("r")) {
            body();
        } catch (RuntimeException e) {
            System.out.println("compiler:     " + e.getMessage() + ", suppressed "
                    + e.getSuppressed()[0].getMessage());
        }
    }
}

Output:

Output
close r
hand-written: body, suppressed close r
  close r
compiler:     body, suppressed close r
  • Both versions closed the resource once and reported the body's exception with the close failure suppressed. The hand-written version is what javac produces, apart from details such as how it avoids calling addSuppressed on the same exception twice.
  • The resource variable is implicitly final, and the null check before close() is why a null resource is allowed.
  • The catch (Throwable t) that rethrows t compiles even though body() declares no checked exceptions, thanks to Java 7's precise rethrow analysis: the compiler knows t can only be what the try block throws.

Failures while opening, and the nested-constructor leak

A resource can also fail while it is being created. Three cases show what try-with-resources does then, including one leak it cannot prevent. The program tracks which resources are open in a list.

Java
import java.util.ArrayList;
import java.util.List;

public class OpenFailures {

    static final List<String> OPEN = new ArrayList<>();

    static class Res implements AutoCloseable {
        final String name;

        Res(String name, boolean failToOpen) {
            if (failToOpen) {
                throw new IllegalStateException("cannot open " + name);
            }
            this.name = name;
            OPEN.add(name);
        }

        @Override
        public void close() {
            OPEN.remove(name);
        }
    }

    // A wrapper, like BufferedReader around FileReader, whose constructor can fail
    static class Wrapper implements AutoCloseable {
        final Res inner;

        Wrapper(Res inner, boolean fail) {
            if (fail) {
                throw new IllegalArgumentException("bad buffer size");
            }
            this.inner = inner;
        }

        @Override
        public void close() {
            inner.close();
        }
    }

    public static void main(String[] args) {
        // 1. The second resource fails to open: the first one is still closed
        try (Res a = new Res("a", false); Res b = new Res("b", true)) {
            System.out.println("never reached " + a + b);
        } catch (IllegalStateException e) {
            System.out.println("1. " + e.getMessage() + "; still open: " + OPEN);
        }

        // 2. Nesting the constructors: if the wrapper fails, nobody closes the inner resource
        try (Wrapper w = new Wrapper(new Res("inner", false), true)) {
            System.out.println("never reached " + w);
        } catch (IllegalArgumentException e) {
            System.out.println("2. " + e.getMessage() + "; still open: " + OPEN + "  <- leaked");
        }
        OPEN.clear();

        // 3. Declaring each resource separately closes the inner one too
        try (Res inner = new Res("inner", false); Wrapper w = new Wrapper(inner, true)) {
            System.out.println("never reached " + w);
        } catch (IllegalArgumentException e) {
            System.out.println("3. " + e.getMessage() + "; still open: " + OPEN);
        }
    }
}

Output:

Output
1. cannot open b; still open: []
2. bad buffer size; still open: [inner]  <- leaked
3. bad buffer size; still open: []
  1. When the second resource failed to open, the first one had already been assigned to its variable, so it was closed, and nothing was left open. A resource whose constructor throws is never assigned, so it has nothing to close.
  2. With new Wrapper(new Res(...)) as a single resource, the inner resource opened, then the wrapper's constructor threw. The inner object was never a declared resource, so nobody closed it, and it leaked. The same happens with new BufferedReader(new FileReader(file), size) when the outer constructor fails.
  3. Declaring the inner and outer objects as two resources fixed it: when the wrapper failed, the inner resource was closed. For wrappers whose constructors cannot fail in practice, nesting is common and usually fine; for anything that can, declare each layer.

Real resources: leaked file handles, and any cleanup as AutoCloseable

A leaked resource rarely fails immediately; it just stays open. The program opens a small file 200 times with Files.lines, which keeps the file open until its stream is closed, and counts the process's open file descriptors through the operating system MXBean (available on Linux and macOS). Then it uses a method reference to make a lock's unlock work with try-with-resources.

Java
import com.sun.management.UnixOperatingSystemMXBean;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;

public class RealResources {

    static long openFiles() {
        return ((UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean())
                .getOpenFileDescriptorCount();
    }

    @SuppressWarnings("try")       // the unlock resource is never used in the body, on purpose
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("lines", ".txt");
        Files.writeString(file, "a\nb\nc\n");

        // 1. Files.lines keeps the file open until the stream is closed
        long before = openFiles();
        List<Stream<String>> leaked = new ArrayList<>();
        for (int i = 0; i < 200; i++) {
            Stream<String> s = Files.lines(file);
            s.count();                                  // consumed, but never closed
            leaked.add(s);
        }
        System.out.println("200 Files.lines without close: about +"
                + Math.round((openFiles() - before) / 10.0) * 10 + " open file descriptors");
        leaked.forEach(Stream::close);

        before = openFiles();
        for (int i = 0; i < 200; i++) {
            try (Stream<String> s = Files.lines(file)) {
                s.count();
            }
        }
        System.out.println("200 Files.lines in try:        +" + (openFiles() - before)
                + " open file descriptors");

        // 2. Any cleanup can be made AutoCloseable with a lambda, for example an unlock
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try (AutoCloseable unlock = lock::unlock) {
            System.out.println("inside: lock held = " + lock.isHeldByCurrentThread());
        } catch (Exception e) {
            throw new IllegalStateException(e);           // AutoCloseable.close throws Exception
        }
        System.out.println("after:  lock held = " + lock.isHeldByCurrentThread());
        Files.delete(file);
    }
}

Output:

Output
200 Files.lines without close: about +200 open file descriptors
200 Files.lines in try:        +0 open file descriptors
inside: lock held = true
after:  lock held = false
  • Without closing, 200 streams left about 200 file descriptors open, even though every stream had been read to the end: reading to the end does not close a Files.lines stream. Processes have a limit on open files, often 1,024 by default on Linux, after which every open fails with "Too many open files". With try-with-resources, the count did not change.
  • AutoCloseable is a functional interface, so lock::unlock is a valid resource. The lock was held inside the block and released after it. The catch for Exception is needed because AutoCloseable.close() declares throws Exception; your own resource types should declare a narrower exception, or none.
  • Streams from Files.lines, Files.list, Files.walk and Files.newDirectoryStream must all be closed. Ordinary collection streams hold nothing and need no closing.

Writing your own AutoCloseable

A few rules make a resource class pleasant and safe to use:

  • Declare close() with the narrowest exception, ideally none, so callers do not need a catch (Exception e). Closeable types should throw only IOException.
  • Make close() idempotent: a second call should do nothing. The Closeable contract requires it, and the AutoCloseable Javadoc strongly encourages it, because callers and frameworks do close things twice.
  • Release in reverse order of acquisition, and if releasing one part fails, still try to release the others, collecting failures with addSuppressed.
  • Do not throw InterruptedException from close(); the Javadoc warns that suppressing it would hide an interrupt.
  • For a resource that owns native memory or handles, add a Cleaner as a safety net, but never rely on it instead of close().

Choosing how to release resources

Resource handling recipes
SituationUse
Any object with close()try-with-resources, even for one resource
Several resources that depend on each otherDeclare them in one statement, in acquisition order
Wrappers whose constructors can failDeclare each layer as its own resource
A resource created earliertry (existing) { ... } (Java 9)
Cleanup that is not a resource, such as an unlockA lambda or method reference as AutoCloseable, or plain try/finally
Executorstry (ExecutorService pool = ...) since Java 19
Diagnosing a failureLook at getSuppressed(); stack traces print them under "Suppressed:"

See exception handling for try, catch and finally in general, and reading text files for resources in everyday I/O.