Skip to main content
Exception handling · Topic 7 of 7

Multi-catch and rethrow

Definition​

A multi-catch handles several exception types in one block, written catch (A | B e). Use it when the handling is the same. You can also rethrow an exception after logging it, so callers still see the failure.

Example code​

One handler for two kinds of failure

class Demo {
static int divide(String a, String b) {
try {
return Integer.parseInt(a) / Integer.parseInt(b);
} catch (NumberFormatException | ArithmeticException e) { // same handling for both
System.out.println("Cannot calculate: " + e.getMessage());
throw e; // log it, then let the caller know
}
}

public static void main(String[] args) {
System.out.println(divide("10", "2"));
for (String[] pair : new String[][] {{"10", "0"}, {"ten", "2"}}) {
try {
divide(pair[0], pair[1]);
} catch (RuntimeException e) {
System.out.println("caller saw " + e.getClass().getSimpleName());
}
}
}
}

// Output:
// 5
// Cannot calculate: / by zero
// caller saw ArithmeticException
// Cannot calculate: For input string: "ten"
// caller saw NumberFormatException

Finished this page? Track your progress (saved only in your browser).