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()tryfinally
- Every resource declared in the parentheses is closed when the block ends, whether it ends normally, by
, or by an exception.return - 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
also throws, the body's exception is the one that propagates, and the exception fromclose() is attached to it as a suppressed exception instead of replacing it.close() - Any
andcatch clauses run after the resources have been closed.finally
The statement works with any object that implements java.lang.AutoCloseablevoid close() throws Exceptiontrycatchfinally
| Piece | Since | Notes |
|---|---|---|
java.io.Closeable | Java 5 | close() throws IOException |
AutoCloseable | Java 7 | Closeableclose() |
Throwable.addSuppressedgetSuppressed | Java 7 | Where exceptions from close() |
Existing effectively final variables as resources: try (r) | Java 9 | No need to declare a new variable for a resource made earlier |
ExecutorServiceForkJoinPoolAutoCloseable | Java 19 | close() |
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 catchfinallynull
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:
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,
thendb , and closed in reverse,file thenfile . With a reader wrapped around a stream, the outer one is closed before the inner one, which is what both expect.db - When the body threw,
ran first, then theclose block, thencatch . By the time afinally block runs, the resource is already closed and cannot be used for clean-up work.catch 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.try (existing)- A resource that is
is allowed, and the generated code simply skips itsnull . That keeps code likeclose() free of null checks.try (var in = optionalStreamOrNull())
Suppressed exceptions
A resource whose useclosetryfinallyclose
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:
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,
beforeb , and both of their failures were attached witha , in that order. A stack trace prints them under "Suppressed:", so nothing is lost.addSuppressed - With
/try , the exception thrown byfinally in theclose() 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.finally - When only
fails, its exception is the primary one. A write that is buffered and flushed only inclose() fails exactly this way, so a successful body does not mean the data reached the disk.close()
The @SuppressWarnings("try")mainjavac -Xlint
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()
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:
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
produces, apart from details such as how it avoids callingjavac on the same exception twice.addSuppressed - The resource variable is implicitly
, and the null check beforefinal is why aclose() resource is allowed.null - The
that rethrowscatch (Throwable t) compiles even thought declares no checked exceptions, thanks to Java 7's precise rethrow analysis: the compiler knowsbody() can only be what thet block throws.try
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.
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:
1. cannot open b; still open: []
2. bad buffer size; still open: [inner] <- leaked
3. bad buffer size; still open: []
- 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.
- With
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 withnew Wrapper(new Res(...)) when the outer constructor fails.new BufferedReader(new FileReader(file), size) - 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.linesunlock
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:
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
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.Files.lines is a functional interface, soAutoCloseable is a valid resource. The lock was held inside the block and released after it. The catch forlock::unlock is needed becauseException declaresAutoCloseable.close() ; your own resource types should declare a narrower exception, or none.throws Exception- Streams from
,Files.lines ,Files.list andFiles.walk must all be closed. Ordinary collection streams hold nothing and need no closing.Files.newDirectoryStream
Writing your own AutoCloseable
A few rules make a resource class pleasant and safe to use:
- Declare
with the narrowest exception, ideally none, so callers do not need aclose() .catch (Exception e) types should throw onlyCloseable .IOException - Make
idempotent: a second call should do nothing. Theclose() contract requires it, and theCloseable Javadoc strongly encourages it, because callers and frameworks do close things twice.AutoCloseable - 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
fromInterruptedException ; the Javadoc warns that suppressing it would hide an interrupt.close() - 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
| Situation | Use |
|---|---|
Any object with close() | try-with-resources, even for one resource |
| Several resources that depend on each other | Declare them in one statement, in acquisition order |
| Wrappers whose constructors can fail | Declare each layer as its own resource |
| A resource created earlier | try (existing) { ... } |
| Cleanup that is not a resource, such as an unlock | A lambda or method reference as AutoCloseabletryfinally |
| Executors | try (ExecutorService pool = ...) |
| Diagnosing a failure | Look at getSuppressed() |
See trycatchfinally