Try-with-resources
What you will learn
Try-with-resources automatically invokes close on resources implementing AutoCloseable when execution leaves the block. It expresses resource ownership directly.
- Predict the order of resource closing on success and failure.
- Distinguish an original exception from a suppressed cleanup failure.
Each example is a standalone Main.java. Compile with javac --release 21 Main.java and run with java Main. Java 25 execution remains unverified.
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 lease = new Lease("A")) { lease.use(); } System.out.println("Done"); }}Expected output:
Use AClose ADoneThe resource is closed before the following statement. The Lease is an in-memory model, not an operating-system handle.
Resource lifetime and suppressed exceptions
Declare resources inside parentheses after try, separated by semicolons. An already declared final or effectively final resource may be referenced in Java 9 and later. Resources initialize from left to right and non-null resources close in reverse order, including ones created before a later initializer fails. If the body fails and closing also fails, the body exception normally remains primary and the close failure is available through getSuppressed(). If only closing fails, that failure propagates normally. A custom close implementation may declare a narrower exception type or none; AutoCloseable.close itself declares Exception. Automatic close is not garbage collection. Close only resources you own: closing a shared stream may affect other code. The examples use in-memory resources with no external I/O.
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()); } }}Expected output:
Use AUse BClose BClose AWork failedBoth close calls occur before catch, even after an exception in the body.
A practical variation
import java.io.IOException;class FailingLease implements AutoCloseable { void use() throws IOException { throw new IOException("Read failed"); } public void close() throws IOException { throw new IOException("Close failed"); }}public class Main { public static void main(String[] args) { try (FailingLease lease = new FailingLease()) { lease.use(); } catch (IOException e) { System.out.println(e.getMessage()); System.out.println(e.getSuppressed()[0].getMessage()); } }}Expected output:
Read failedClose failedThe body exception is primary; the close exception is attached, not silently discarded.
Common mistakes
Do not assume automatic cleanup means no errors can occur. Do not manually close the same resource again unless its contract permits repeated closing.
Practice
Build an in-memory Audit resource that prints opened, work, closed. Use try-with-resources and throw an IllegalStateException during work in a second scenario. Confirm close precedes the catch.
Hints:
- Implement AutoCloseable with public void close().
- Use a catch outside the resource block to report the failure.
Related reference topics: Java try-with-resources, Java AutoCloseable.close(), Java Throwable.getSuppressed(). Next: Console inventory project.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Try-with-resources — knowledge check
Apply Java exception and inventory contracts using Java 21-compatible examples.
Which interface enables resource management?
A then B are acquired. What is close order?
Body and close both throw IOException. Which is primary?
Where can you inspect a suppressed exception?
If the second resource initializer throws, what happens to the first non-null resource?