Codectionary / Developer documentation / Java

Automatic Cleanup with try-with-resources

Close AutoCloseable resources reliably when a block finishes normally or exceptionally.

What it is and why to use it

Files, connections and similar resources can need prompt cleanup even if a computation throws. A try-with-resources statement closes successfully initialised resources when control leaves its block. This is deterministic cleanup; it is separate from garbage collection reclaiming object memory.

How it works

A resource must implement AutoCloseable. Multiple resources are closed in reverse declaration order. The small demonstration class logs its cleanup so the order is observable without opening files. Real resource classes perform their own cleanup in close; simply implementing the interface does not release anything automatically outside a resource statement.

Common mistakes and limitations

Do not close a shared resource that the method does not own. Avoid returning a resource from inside a try block that already closes it. Exceptions from close still need appropriate handling.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

try (Resource first = ...; Resource second = ...) { /* work */ }

Examples

Automatic Cleanup with try-with-resources

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  static class Resource implements AutoCloseable {
    private final String name;
    Resource(String name) { this.name = name; }
    public void close() { System.out.println("closed " + name); }
  }

  public static void main(String[] args) {
    try (Resource first = new Resource("first");
         Resource second = new Resource("second")) {
      System.out.println("work");
    }
  }
}
  1. The resource header initialises first, then second, before entering the block.
  2. The block prints work; leaving it calls second.close() followed by first.close().
  3. The output demonstrates stack-like cleanup order. If the body and cleanup both throw, the body’s exception is primary and cleanup exceptions can be attached as suppressed exceptions.
  4. Expected output: work closed second closed first

Best practices

  • Use try-with-resources for resources you own.
  • Catch specific failures at a boundary that can recover or explain them.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading