Command Palette

Search for a command to run...

Back to the lesson: Topic 7.7 — Multi-catch and Rethrowing
Core Java · Example 2 of 3 Java 7+

Precise rethrow and the multi-catch variable's type

A multi-catch, catch (A | B e), handles several unrelated exception types with one block. Rethrowing passes an exception on after doing something with it, and Java 7's precise rethrow lets you catch broadly while still declaring only the exceptions that can really occur.

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 a method describe(Object o) that does ((String) o).charAt(5) and uses one multi-catch for ClassCastException | StringIndexOutOfBoundsException to return "invalid: " + simple class name. Test with "hello world", 42 and "hi".

02

Write static void load(String name) throws java.io.IOException, InterruptedException whose body calls helpers declared to throw those two, catches Exception e, prints cleanup for <name>, and rethrows. Show it working for a name that triggers each failure.

03

Write a withRetry that retries only IllegalStateException (temporary) but rethrows IllegalArgumentException (permanent) immediately. Show both behaviours.

Explain it without notes

01

What is multi-catch, and what are its restrictions?

02

What is the static type of a multi-catch parameter, and why is it final?

03

What is precise rethrow, and when does it stop working?

04

When should you rethrow, wrap, or handle an exception?

Precise rethrow and the multi-catch variable's type Java 7+
Sign in to run this example in your browser.

Expected output

step 0 ok
log: step 1 failed with FileNotFoundException
recoverable: config.yml
log: step 2 failed with TimeoutException
recoverable: db took 5s
log: step 3 failed with IllegalStateException
bug: bug in step 3