Java ProgramsExceptionsMulti-Catch

Multi-Catch in Java

intermediate·  Exceptions  ·  Error Handling

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.

Input
process(1) triggers an array index failure, process(2) triggers a number format failure
Output
Caught: ArrayIndexOutOfBoundsException Caught: NumberFormatException

Java Program

Java
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

Caught: ArrayIndexOutOfBoundsException Caught: NumberFormatException

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.

How It Works
  1. 1catch (ArrayIndexOutOfBoundsException | NumberFormatException e) matches either exception type with a single block.
  2. 2Calling process(1) triggers the array-index branch, throwing an ArrayIndexOutOfBoundsException.
  3. 3Calling process(2) triggers the number-parsing branch instead, throwing a NumberFormatException.
  4. 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.

Key Concepts

multi-catchpipe operatortry / catch

Related Programs