finally and return: the surprises
The first line prints before 'returned 1' because the method call runs while the string is being built.
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
finally set value to 99
returned 1, value is now 99
returned 2
finally returned normally
object returned: ab