SteelReed

Search

Search posts, questions…

Java CoreQuestion 25 / 43

Middle

What problem does try-with-resources solve? What is a suppressed exception?

Short answer

try-with-resources calls close() for you when the block ends, whether it succeeded or failed. If both the body and close() fail, the original error is kept.

finishes or throwsclose also throwsOpen c, then pstry body runsclose ps, then creverse orderaddSuppressed ontobody's exceptioncatch, finally run after

3 points to say:

  1. Resources close in reverse order of opening.
  2. The close() error goes into getSuppressed().
  3. catch and finally run after closing.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.