Multiple Catch Blocks in Java
beginner· Exceptions · Error Handling
Problem
A single try block can be followed by several catch blocks, one per exception type, and only the one matching whatever actually gets thrown ever runs.
Given code that could fail in two different ways, catch each kind of failure with its own dedicated catch block.
Input
numbers = {1, 2, 3}, access index 5
Output
Array error: Index 5 out of bounds for length 3
Java Program
Java
public class MultipleCatchBlocks {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println("Value: " + numbers[5]); // throws before the next line ever runs
int parsed = Integer.parseInt("abc");
System.out.println("Parsed: " + parsed);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array error: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Parsing error: " + e.getMessage());
}
}
}Output
Array error: Index 5 out of bounds for length 3
Core Logic
Stacking one catch block per exception type after a single try lets one block handle an array-access failure and another handle a parsing failure, without merging their logic together.
How It Works
- 1The
tryblock first accessesnumbers[5], which is out of bounds for a 3-element array. - 2As soon as that line throws, control jumps straight to the matching catch — the
Integer.parseInt("abc")line right after it never runs at all. - 3
catch (ArrayIndexOutOfBoundsException e)matches this specific failure and prints its message. - 4The second
catch (NumberFormatException e)block exists for a different failure mode — it would only run if the parsing line had been reached and failed instead.
Since
numbers[5] fails first, only the array-access catch block ever executes, printing "Array error: Index 5 out of bounds for length 3".💡
Key Point: Only one catch block runs per try — the first line that throws determines which one, and everything else in the try block, including any other risky line, is skipped entirely.
Key Concepts
multiple catch blocksArrayIndexOutOfBoundsExceptionNumberFormatException