Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 201 ยท Exceptions

try-with-resources

Learn Java try-with-resources - AutoCloseable and Closeable, closing order, multiple resources, suppressed exceptions, failures while opening and writing your own resources.

Some objects hold on to something outside your program: an open file, a network socket, a database connection, a thread pool. These resources must be closed when you're done, or the operating system eventually runs out of file handles, the database out of connections, and your program fails in ways that are hard to trace. Closing reliably is harder than it looks, because an exception can skip the line that closes the resource.

try-with-resources (Java 7) solves this. You declare the resources in parentheses after try, and Java closes them automatically when the block ends, in the right order, whether it ends normally or with an exception. It also handles the tricky case where closing itself fails. This lesson covers the syntax, the AutoCloseable interface, closing order, what happens when opening or closing fails, suppressed exceptions, and how to write your own resource classes.

The problem with closing by hand

Here's the pre-Java 7 way to read the first line of a file safely, using finally (Exceptions and try-catch):

Java
BufferedReader reader = null;
try {
    reader = Files.newBufferedReader(path);
    return reader.readLine();
} finally {
    if (reader != null) {          // opening may have failed
        try {
            reader.close();        // close() can throw too...
        } catch (IOException e) {
            // ...and then what? Ignore it? Log it?
        }
    }
}

Eleven lines of ceremony around one line of work, with three classic bugs waiting to happen: forgetting the null check, forgetting finally altogether, and an exception from close() replacing the more important exception from readLine(). With two or three resources, the nesting gets worse. The same code with try-with-resources:

Java
try (BufferedReader reader = Files.newBufferedReader(path)) {
    return reader.readLine();
}

The syntax

Java
try (ResourceType name = expression) {
    // use name
}   // name.close() is called here automatically
  • The resource must implement java.lang.AutoCloseable, an interface with one method: void close() throws Exception.
  • The resource variable is implicitly final and scoped to the try block.
  • close() is called exactly once when the block ends, however it ends: normally, by return, break, continue, or an exception.
  • You may still add catch and finally blocks; they run after the resources are closed.

Most I/O classes implement java.io.Closeable, a sub-interface of AutoCloseable whose close() throws only IOException. Others, like JDBC's Connection, implement AutoCloseable directly.

To see exactly when close() runs, here's a resource class that announces each step:

Java Opening and closing order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Several resources are separated by semicolons, and they're opened left to right and closed in reverse order. That's what you want: file might depend on db, so it must be closed first. This is the same "last opened, first closed" order as nested blocks.

Also notice that close() here declares no exception. An implementation may narrow the throws Exception of AutoCloseable.close() (see Throwing Exceptions for the overriding rule), and then callers don't need to catch anything.

Exceptions, catch and finally

When the body throws, Java first closes the resources, then looks for a matching catch, then runs finally. The resource is never open while your error handling runs:

Java Resources are closed before catch and finally run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the failing run, step 2 is replaced by the exception, but disconnect still happens, before catch. var works for resource declarations, as this example shows.

When opening fails

What if the second of three resources can't be opened? Java closes only the resources that were successfully initialized, in reverse order, and then propagates the exception. A resource whose initializer threw doesn't exist, so there's nothing to close:

Java A resource fails to open

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

cache opens, queue fails, log is never attempted. Only cache is closed. Getting this right by hand requires a nested try/finally per resource, which is exactly what the compiler generates for you.

A resource expression may also evaluate to null. That's allowed: Java simply skips close() for a null resource instead of throwing NullPointerException.

Suppressed exceptions

Now the hard case: the body throws an exception, and then close() throws another one while cleaning up. Which one should the caller see?

The body's exception is almost always the important one; the close failure is often just a consequence of it. So try-with-resources propagates the body's exception and attaches the close exception to it as a suppressed exception. Nothing is lost: getSuppressed() returns the extra exceptions, and stack traces print them under Suppressed:.

Compare that with the hand-written finally version, where the close exception silently replaces the original:

Java Suppressed exceptions vs exceptions lost in finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The finally version reports only "flush failed on close", and the real cause, the full disk, is gone. The try-with-resources version reports "disk full" and keeps the close failure as a suppressed exception. With several resources, each close failure is added to the list, in closing order.

If the body finishes normally and only close() throws, there's nothing to suppress: the close exception propagates as the main exception. You can also attach suppressed exceptions yourself with addSuppressed(...), which is handy when you write cleanup code that must try several steps and report all failures.

Using real resources

The JDK has dozens of AutoCloseable classes. The ones you'll use most:

Resource Where it comes from
BufferedReader, BufferedWriter Files.newBufferedReader/Writer(path) (Byte and Character Streams)
InputStream, OutputStream Files.newInputStream(path), sockets, ZipInputStream
Stream<String> from Files.lines(path), Stream<Path> from Files.list/walk They hold an open file or directory handle
Scanner Over a file or stream (but don't close one that wraps System.in if you'll read input again)
Socket, ServerSocket, HttpClient TCP Sockets, The Java HTTP Client
ExecutorService Since Java 19, close() waits for submitted tasks (Executors and Thread Pools)
JDBC Connection, PreparedStatement, ResultSet Database access (Advanced Java)
Java Writing and reading a file with try-with-resources

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first block shows a subtle benefit: a BufferedWriter keeps data in memory until it's flushed, and closing it flushes. Without the close, the file could end up empty or truncated. The Files.lines stream is easy to forget: it reads lazily from an open file, so it must be closed like a reader, while a stream over a List needs no closing.

Using an existing variable (Java 9)

If a resource was created earlier and the variable is final or effectively final, you can name it in the parentheses instead of declaring a new variable:

Java
BufferedReader reader = Files.newBufferedReader(path);   // never reassigned
try (reader) {
    IO.println(reader.readLine());
}

That's useful when the resource is created by other code or passed in as a parameter. Be careful, though: if something between the creation and the try throws, the resource is never closed. Declaring it inside the parentheses is safer whenever you can.

When you need a resource only for its open/close effect and never use the variable, Java 22's unnamed variable keeps the compiler quiet: try (var _ = tracker.start("import")) { ... }.

Writing your own resource

Any class that must release something should implement AutoCloseable so users can manage it with try-with-resources. A few guidelines make it behave well:

  • Narrow the throws clause. Declare close() without exceptions, or with IOException (by implementing Closeable), so callers don't have to catch a bare Exception.
  • Make close() idempotent: calling it twice should be harmless. Closeable requires this; for AutoCloseable it's strongly recommended.
  • Reject use after close with IllegalStateException.
  • Don't throw InterruptedException from close(): suppression could hide the thread's interrupt status. (The compiler's -Xlint:try option warns about this.)
Java A well-behaved custom resource

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last part prints rollback [] once: the first close() rolls back the (empty) uncommitted transaction, and the second call returns immediately. This "commit or roll back on close" pattern is how real transaction APIs work: if the block finishes without calling commit(), for example because an exception left it early, close() undoes the changes. The caller can't forget the cleanup, because the language does it.

Not everything that needs releasing is AutoCloseable. A ReentrantLock is unlocked with the classic lock(); try { ... } finally { unlock(); } pattern (Locks and Conditions), and plain objects in memory are reclaimed by the garbage collector without any closing (Memory and Garbage Collection). Use try-with-resources for things that hold operating-system or external resources.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In try (var a = open("A"); var b = open("B")) { ... }, in what order are the resources closed?

    Resources are opened left to right and closed in reverse order, so the most recently opened resource is closed first.
  2. 2. The body of a try-with-resources throws exception X, and then close() throws exception Y. What does the caller catch?

    The body's exception is propagated, and the close exception is attached to it as a suppressed exception, so no information is lost.
  3. 3. In try (var r = new Res()) { throw new RuntimeException(); } catch (RuntimeException e) { IO.println("catch"); }, when does r.close() run?

    Resources are always closed first, then catch and finally blocks run, so the resource is never open during error handling.
  4. 4. The first of two resources opens, but the second resource's constructor throws. What happens?

    Only successfully initialized resources are closed, in reverse order. The failing resource was never created, and the body doesn't run.
  5. 5. Which class can be used in try-with-resources?

    The resource type must implement java.lang.AutoCloseable. Closeable extends it, so all standard I/O classes qualify, and your own classes can implement it too.

Summary

  • try-with-resources declares resources in try (...) and closes them automatically, however the block ends; the resource type must implement AutoCloseable (or Closeable).
  • Multiple resources are separated by semicolons, opened left to right and closed in reverse order; catch and finally run after closing.
  • If a resource fails to open, only the ones already opened are closed; null resources are skipped.
  • If the body throws and close() throws too, the body's exception wins and the close exception is suppressed (getSuppressed(), Suppressed: in traces), unlike hand-written finally code that loses the original.
  • Close readers, writers, Files.lines streams, sockets, connections and executors this way; since Java 9, an effectively final variable can be named directly in the parentheses.
  • Your own resources should narrow close()'s throws, be idempotent, and reject use after close.

Next: Exception Handling Best Practices, where you'll pull everything in this chapter together into habits that keep programs robust.