Command Palette

Search for a command to run...

Back to the lesson: Topic 7.6 — try-with-resources
Core Java · Example 1 of 3 Java 7+

Open, use, close in reverse, then catch and finally

Both resources are closed before the catch block runs.

try-with-resources declares objects that must be closed (files, sockets, database connections) in parentheses after try. Java closes them automatically, in reverse order, however the block ends, and keeps any failure from close() as a suppressed exception instead of losing the original error.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a Connection-like class FakeDb implementing AutoCloseable that prints connect, query <sql> and disconnect, and refuses queries after close with IllegalStateException. Use it in try-with-resources, then try a query on it after the block.

02

Write static String join(String... parts) that builds the result through a StringWriter wrapped in a PrintWriter declared as two resources, separating parts with |. Print join("a", "b", "c").

03

Two resources: Gate("outer") and Gate("inner"), where the inner one's close() throws. The body throws IllegalStateException("work failed"). Predict and print the primary message and the suppressed messages.

Explain it without notes

01

What problem does try-with-resources solve, and what does it require of a resource?

02

In what order are resources closed, and when relative to catch and finally?

03

What are suppressed exceptions, and how do you read them?

04

What changed in Java 9 for try-with-resources?

05

How would you design your own class to be used as a resource?

Open, use, close in reverse, then catch and finally Java 7+
Sign in to run this example in your browser.

Expected output

open A
open B
use A
use B
close B
close A
catch: boom
finally
-- null resource
body runs, null is skipped on close