Java try-with-resources: AutoCloseable, Closing Order and Suppressed Exceptions (OCP 21)
try-with-resources for the OCP 21 exam: AutoCloseable versus Closeable, declaring resources, var and effectively final resources, scope, reverse closing order, the implicit finally, close() exceptions, suppressed exceptions and what happens when a finally block throws.
kvi5hnuCode Sprout team member7 min readOn this page
Files, sockets, database connections and similar objects are resources. They hold something outside the JVM, so they must be closed, and garbage collection won't do it for you. Forget to close them and you get a resource leak: file handles or connections run out.
Before Java 7, safe cleanup needed a finally block containing its own try/catch:
Reader in = null;
try {
in = new FileReader("seats.csv");
// read...
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try { in.close(); } catch (IOException e2) { e2.printStackTrace(); }
}
}
try-with-resources (also called automatic resource management) replaces all of that:
try (Reader in = new FileReader("seats.csv")) {
// read...
} catch (IOException e) {
e.printStackTrace();
}
The compiler generates an implicit finally that closes in, whether the body finishes normally or throws.
AutoCloseable and Closeable
Only objects whose type implements java.lang.AutoCloseable can be resources:
public interface AutoCloseable {
void close() throws Exception;
}
AutoCloseable | Closeable | |
|---|---|---|
| Package | java.lang | java.io |
| Relationship | parent | extends AutoCloseable |
close() declares | throws Exception | throws IOException |
Should close() be idempotent (safe to call twice)? | recommended | required by the contract |
| Used by | your own classes, JDBC, Scanner, streams | Reader, Writer, InputStream, OutputStream |
Overriding rules apply to the implementation of close(). It may declare Exception, something narrower, or nothing at all. What callers must handle depends on what the resource's declared type says close() throws:
class Valve implements AutoCloseable {
public void close() { } // declares nothing
}
try (Valve v = new Valve()) { } // no catch needed
try (AutoCloseable v = new Valve()) { } // DOES NOT COMPILE: close() of AutoCloseable throws Exception
try (String s = "x") { } doesn't compile, because String isn't AutoCloseable.
Declaring resources
try (var hot = new Valve("hot"); // var is fine: resources are local variables
Valve cold = new Valve("cold");) { // a trailing semicolon is allowed
hot.use();
cold.use();
}
| Rule | Doesn't compile |
|---|---|
| Separate resources with semicolons, each with its own type | try (Valve a = new Valve(), b = new Valve()), try (Valve a = new Valve(), Valve b = new Valve()) |
| Resources are implicitly final | try (Valve a = new Valve()) { a = null; } |
| A resource is in scope only in the try block | using a inside catch or finally |
catch and finally are both optional | (a bare try (…) { } is legal, unlike a plain try) |
| Each resource needs a variable | try (new Valve()) { } |
Using existing variables (Java 9+)
A resource can also be a variable declared before the try, as long as it's final or effectively final. Just name it in the resource list:
final Valve main = new Valve("main");
Valve spare = new Valve("spare"); // effectively final
try (main; var extra = new Valve("extra"); spare) {
main.use();
}
// closes spare, then extra, then main
If the variable is reassigned anywhere, even after the try, it isn't effectively final, so try (spare) doesn't compile. A final field works too, as in try (this.pump). A non-final field doesn't.
Two consequences of this form:
- The variable is still in scope after the
try, but the object is now closed. Using it afterwards compiles, but typically throws at runtime (for exampleIOException: Stream closed). - Anything that happens to the object before the
tryisn't protected. If an exception is thrown between creating the resource and entering thetry, it never gets closed.
Order of operations

- Resources are opened in declaration order.
- The body runs.
- Resources are closed in reverse order, as the implicit finally. This happens before any
catchorfinallyyou wrote. - A matching
catchblock runs, if an exception is propagating. - Your own
finallyruns.
try (Valve hot = new Valve("hot"); Valve cold = new Valve("cold")) {
hot.use(); cold.use();
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
System.out.print("catch ");
} finally {
System.out.print("finally");
}
// open-hot open-cold use-hot use-cold close-cold close-hot catch finally
Special cases, all verified:
- A resource is
null.close()isn't called for it, and there's no exception. - A resource fails to open. It isn't closed, since it doesn't exist. Resources opened before it are closed, in reverse order. Resources declared after it are never opened.
Suppressed exceptions
What if close() throws? There are three cases:
| Body | close() | Exception that reaches catch or the caller |
|---|---|---|
| finishes normally | throws Y | Y |
| throws X | finishes normally | X |
| throws X | throws Y | X, with Y attached as a suppressed exception |
The first exception is the primary one. Every later exception from closing is added to it with addSuppressed and can be read back with getSuppressed(), which returns a Throwable[].
try (Valve drain = new Valve("drain", /* jamOnClose */ true)) {
throw new IllegalArgumentException("leak in body");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // leak in body
for (Throwable t : e.getSuppressed())
System.out.println(t.getMessage()); // drain jammed while closing
}
catchblocks match only the primary exception. If the primary is anIllegalArgumentExceptionand you onlycatch (IllegalStateException e), the catch doesn't run, even though a suppressed exception has that type. The uncaught primary propagates, and its stack trace lists the suppressed ones underSuppressed:.- With several failing resources and a successful body, the first
close()to fail is primary. That's the last declared resource that throws, because closing runs in reverse. The others are suppressed. - A
finallyyou write still follows the old rules. If yourfinallythrows, its exception replaces everything, including the primary and its suppressed list. Suppression happens only for the implicit close.
Suppressed exceptions aren't only for try-with-resources. Any Throwable has addSuppressed(Throwable) and getSuppressed(), so your own cleanup code can use them.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Java 9 allowed effectively final variables in the resource list. Java 22 allows an unnamed resource,
try (var _ = lock()), which isn't on 1Z0-830.
Exam traps from this article
A complete example
A plumbing simulation. Valve is a resource that logs every open, use and close, and can be told to jam when closing or to fail when opening. Seven scenarios cover every rule from this article, and each prints its event log plus any primary and suppressed exceptions.
public class Solution {
static final StringBuilder LOG = new StringBuilder();
// A resource that logs when it opens, is used and closes; it can be told to fail
static class Valve implements AutoCloseable {
private final String name;
private final boolean jamOnClose;
Valve(String name, boolean jamOnClose, boolean failOnOpen) {
if (failOnOpen) {
LOG.append("open-").append(name).append("-FAILED ");
throw new IllegalStateException(name + " would not open");
}
this.name = name;
this.jamOnClose = jamOnClose;
LOG.append("open-").append(name).append(' ');
}
Valve(String name, boolean jamOnClose) {
this(name, jamOnClose, false);
}
void use() {
LOG.append("use-").append(name).append(' ');
}
@Override
public void close() { // no checked exception declared: callers need no catch
LOG.append("close-").append(name).append(' ');
if (jamOnClose) throw new IllegalStateException(name + " jammed while closing");
}
}
static void report(String title, Throwable t) {
System.out.println(title);
System.out.println(" log: " + LOG);
if (t != null) {
System.out.println(" primary: " + t.getMessage());
for (Throwable s : t.getSuppressed()) {
System.out.println(" suppressed: " + s.getMessage());
}
}
LOG.setLength(0);
}
public static void main(String[] args) {
// 1) Close in reverse order, BEFORE the programmer's catch and finally
try (Valve hot = new Valve("hot", false);
Valve cold = new Valve("cold", false)) {
hot.use();
cold.use();
throw new IllegalArgumentException("body failed");
} catch (IllegalArgumentException e) {
LOG.append("catch ");
} finally {
LOG.append("finally");
}
report("1) order", null);
// 2) Java 9+: effectively final variables declared before the try
final Valve main = new Valve("main", false);
Valve spare = new Valve("spare", false); // effectively final: never reassigned
try (main; var extra = new Valve("extra", false); spare) {
main.use();
extra.use();
spare.use();
}
report("2) existing variables as resources", null);
// 3) Body exception is primary; the close() failure is suppressed
try (Valve drain = new Valve("drain", true)) {
drain.use();
throw new IllegalArgumentException("leak in body");
} catch (IllegalArgumentException e) {
report("3) body + close both fail", e);
}
// 4) No body exception: the first close() failure is primary, later ones suppressed
try (Valve a = new Valve("a", true); Valve b = new Valve("b", true)) {
a.use();
b.use();
} catch (IllegalStateException e) {
report("4) two closes fail", e);
}
// 5) A resource that fails to open is not closed; earlier ones are
try (Valve first = new Valve("first", false);
Valve broken = new Valve("broken", false, true)) {
first.use();
broken.use();
} catch (IllegalStateException e) {
report("5) second resource fails to open", e);
}
// 6) A null resource is allowed: close() is simply skipped
try (Valve none = null) {
LOG.append("body with ").append(none);
}
report("6) null resource", null);
// 7) An exception from the programmer's finally replaces everything
try {
try (Valve tap = new Valve("tap", true)) {
tap.use();
throw new IllegalArgumentException("original");
} finally {
LOG.append("finally-throws ");
throwFromFinally();
}
} catch (RuntimeException e) {
report("7) finally throws", e);
}
}
static void throwFromFinally() {
throw new UnsupportedOperationException("from finally (original and suppressed lost)");
}
}
Output:
1) order
log: open-hot open-cold use-hot use-cold close-cold close-hot catch finally
2) existing variables as resources
log: open-main open-spare open-extra use-main use-extra use-spare close-spare close-extra close-main
3) body + close both fail
log: open-drain use-drain close-drain
primary: leak in body
suppressed: drain jammed while closing
4) two closes fail
log: open-a open-b use-a use-b close-b close-a
primary: b jammed while closing
suppressed: a jammed while closing
5) second resource fails to open
log: open-first open-broken-FAILED close-first
primary: broken would not open
6) null resource
log: body with null
7) finally throws
log: open-tap use-tap close-tap finally-throws
primary: from finally (original and suppressed lost)
Points to notice:
- Scenario 1 closed
coldbeforehot, and both closed beforecatchandfinallyran. - Scenario 2 mixed two pre-existing variables with a new declaration. They still closed in reverse order of the resource list:
spare,extra,main. - In scenario 3 the body's exception was primary, and the jammed close was attached as suppressed.
- In scenario 4 the body succeeded, so
b's failed close, which ran first, became primary. - In scenario 5,
brokennever opened and wasn't closed, butfirstwas. - Scenario 7's
finallythrew. The caller saw only that exception, and the original and its suppressed exception were lost. Valve.close()declares no checked exception, so none of thetrystatements needed acatch (Exception e).
Common questions
Can I still write a normal finally with try-with-resources?
Yes. It runs after the resources are closed and after any catch. Use it for cleanup that isn't a resource.
Why make close() idempotent?
Code paths may close a resource twice, for example a wrapper stream closing the stream it wraps. If the second call does nothing, that's harmless.
Does try-with-resources work with locks?
Lock isn't AutoCloseable, so the usual pattern is lock.lock(); try { … } finally { lock.unlock(); }. Chapter 13 covers this.
Summary
- try-with-resources closes every declared
AutoCloseableautomatically, in reverse order, in an implicit finally that runs before yourcatchandfinally. - Declare resources with types (or
var) separated by semicolons, or name existing final or effectively final variables. - Resources are final and scoped to the try block.
catchandfinallyare optional. - Exceptions from closing become suppressed if the body already threw. Read them with
getSuppressed(). - A
finallythat throws still replaces any earlier exception.
Practice quiz
Test yourself with the try-with-resources quiz: 10 exam-style questions with explanations.
Previous: Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
Next: Java Formatting: DecimalFormat, DateTimeFormatter Patterns and String.format (OCP 21)
Related reading
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
- Java Common Exception Classes: Runtime, Checked and Error Types on the Exam (OCP 21)
- Java Exceptions: Checked vs Unchecked, the Throwable Hierarchy and Overriding Rules (OCP 21)
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry
- Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.