An exception in finally hides the real one
The careful version is what try-with-resources generates for you automatically (Topic 7.6).
try marks code that might fail, each catch handles one kind of exception, and finally holds clean-up code that runs whether the try finished normally, returned early, or threw.
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 static int safeParse(String s, int fallback) using try/catch, returning the fallback for bad input. Test with "42", "4x" and null.
Write a loop that tries to divide 60 by each of {3, 0, 5}, printing the result or skip 0, and prints loop done once at the end. Use finally to print checked <n> after each attempt.
Predict, then verify: a method with try { throw new RuntimeException("A"); } catch (RuntimeException e) { throw new RuntimeException("B"); } finally { System.out.println("F"); }. Catch in main and print the message.
Explain it without notes
Walk through every way a try/catch/finally statement can be executed.
Why must catch blocks for subclasses come before catch blocks for superclasses?
What happens when try returns a value and finally also returns or modifies it?
When does finally not run?
Why is throwing from finally dangerous, and what's the fix?
Expected output
careless: java.lang.IllegalArgumentException: cleanup failed
suppressed count: 0
careful: java.lang.IllegalStateException: the real problem
suppressed: java.lang.IllegalArgumentException: cleanup failed