Suppressed exceptions keep the real error on top
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.
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.
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").
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
What problem does try-with-resources solve, and what does it require of a resource?
In what order are resources closed, and when relative to catch and finally?
What are suppressed exceptions, and how do you read them?
What changed in Java 9 for try-with-resources?
How would you design your own class to be used as a resource?
Expected output
primary: body failed
suppressed: close failed: B
suppressed: close failed: A
body ok
primary: close failed: C, suppressed: 0