Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Keywords and Statements

The try-with-resources statement

Reference for Java try-with-resources: AutoCloseable resources, closing order, suppressed exceptions, effectively final variables and common mistakes.

A try-with-resources statement declares one or more resources in parentheses after try. When the block finishes, normally or by an exception, every resource is closed automatically, in the reverse order of declaration. A resource is any object whose class implements java.lang.AutoCloseable (which includes everything that implements java.io.Closeable).

It replaces the error-prone pattern of closing in finally, and it handles the awkward case in which both the body and close() throw: the body's exception wins and the one from close() is attached to it as a suppressed exception.

Java
try (var in = Files.newBufferedReader(path)) {
    return in.readLine();
}

Try it

Java 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.

Java Suppressed exceptions and existing variables

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.

Syntax

Java
try (Type1 r1 = init1; Type2 r2 = init2) {
    body
} catch (SomeException e) {
    ...
} finally {
    ...
}

try (existingFinalVariable) { ... }     // Java 9+
Part Description
Resource declaration A local variable with an initializer, implicitly final. Its type must implement AutoCloseable. May use var.
Existing variable Java 9+: a variable or field access that is final or effectively final can be listed by name.
catch / finally Optional. They run after the resources have been closed.

Usage notes

  • Closing order is reversed: the last resource declared is closed first, so a resource can depend on the earlier ones.
  • If initialization fails for a later resource, the earlier resources are still closed.
  • Suppressed exceptions: if the body throws, exceptions from close() are added with addSuppressed() and can be read with getSuppressed(). If only close() throws, that exception propagates.
  • close() may throw a checked exception (for example IOException or the broad Exception of AutoCloseable.close()), and the compiler requires you to catch or declare it. Implementations can narrow the throws clause or drop it, as Res above does.
  • Make close() idempotent. The Closeable contract says closing twice has no effect; AutoCloseable recommends the same.
  • null resources are allowed: the close call is skipped.
  • Resources are final: you cannot assign to the resource variable inside the block.
  • Wrapped streams: closing the outermost wrapper (for example a BufferedReader) closes the inner ones, so one resource is enough; declaring each separately is still safe.
  • Not for every object: it is meant for things with a clear lifetime like files, sockets, JDBC objects and executors (ExecutorService is AutoCloseable since Java 19).