Exceptions: try-with-resources closes multiple resources in reverse declaration order

Resources declared in a try-with-resources header are closed automatically when the block ends, and they are closed in the reverse of the order they were opened, mirroring how nested resources should be released.

Code
class Resource implements AutoCloseable {
    final String name;
    Resource(String name) {
        this.name = name;
        System.out.println("Opened " + name);
    }
    public void close() {
        System.out.println("Closed " + name);
    }
}
try (Resource first = new Resource("first"); Resource second = new Resource("second")) {
    System.out.println("Using both resources");
}
Output
Opened first
Opened second
Using both resources
Closed second
Closed first
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms