Multi-Catch in Java
Problem
Multi-catch lets one catch block handle several unrelated exception types at once, by joining them with a pipe inside the parentheses, instead of writing a separate catch block for each one that ends up doing the same thing.
Handle two different exception types — one from an array access, one from a number conversion — using a single catch clause.
Java Program
public class MultiCatchExample {
static void process(int choice) {
try {
if (choice == 1) {
int[] arr = new int[2];
System.out.println(arr[5]);
} else {
int n = Integer.parseInt("abc");
System.out.println(n);
}
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) { // one block, either type
System.out.println("Caught: " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) {
process(1);
process(2);
}
}Output
Core Logic
Joining two exception types with a pipe inside one catch clause handles both failure modes identically without duplicating the same catch body twice.
- 1
catch (ArrayIndexOutOfBoundsException | NumberFormatException e)matches either exception type with a single block. - 2Calling
process(1)triggers the array-index branch, throwing anArrayIndexOutOfBoundsException. - 3Calling
process(2)triggers the number-parsing branch instead, throwing aNumberFormatException. - 4Both calls are caught by the exact same catch clause, and
e.getClass().getSimpleName()reports whichever type actually occurred.
process(1) prints "Caught: ArrayIndexOutOfBoundsException", and process(2) prints "Caught: NumberFormatException" — one catch clause, two different exception types.Key Point: Multi-catch only works when the joined types share no ancestor relationship in the handling logic itself — the variable e is implicitly typed as the closest common ancestor of the listed types, so only members shared by both (like getMessage()) are available inside the block, unlike writing separate catch blocks for the exact same two types side by side.