Command Palette

Search for a command to run...

Back to the lesson: Topic 7.2 — try, catch and finally
Core Java · Example 3 of 3

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.

01

Write static int safeParse(String s, int fallback) using try/catch, returning the fallback for bad input. Test with "42", "4x" and null.

02

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.

03

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

01

Walk through every way a try/catch/finally statement can be executed.

02

Why must catch blocks for subclasses come before catch blocks for superclasses?

03

What happens when try returns a value and finally also returns or modifies it?

04

When does finally not run?

05

Why is throwing from finally dangerous, and what's the fix?

An exception in finally hides the real one
Sign in to run this example in your browser.

Expected output

careless: java.lang.IllegalArgumentException: cleanup failed
  suppressed count: 0
careful: java.lang.IllegalStateException: the real problem
  suppressed: java.lang.IllegalArgumentException: cleanup failed