Command Palette

Search for a command to run...

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

Retry, then wrap with the history attached

Real retry code also waits between attempts (with growing delays) and retries only failures that are known to be temporary.

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?

Retry, then wrap with the history attached
Sign in to run this example in your browser.

Expected output

attempt 1 failed: timeout on attempt 1
attempt 2 failed: timeout on attempt 2
tea=42
attempt 1 failed: timeout on attempt 1
attempt 2 failed: timeout on attempt 2
gave up after 2 attempts, cause: timeout on attempt 2
earlier failures kept: 1