Language syntax

Java try-with-resources

Automatically closes acquired non-null resources in reverse order.

Formal Syntax & Structure

java syntaxjava
try (Resource r = new Resource()) { ... }

Working Example

Example Snippetjava
class Lease implements AutoCloseable {    private final String name;    Lease(String name) { this.name = name; }    void use() { System.out.println("Use " + name); }    public void close() { System.out.println("Close " + name); }}
public class Main {    public static void main(String[] args) {        try (Lease a = new Lease("A"); Lease b = new Lease("B")) {            a.use(); b.use();            throw new IllegalStateException("Work failed");        } catch (IllegalStateException e) { System.out.println(e.getMessage()); }    }}
Java Reference