Syntax: Writing Multiple catch Blocks
What You'll Learn
You'll learn the exact syntax for writing multiple catch blocks after a single try block to handle different exception types separately.
The Core Idea
When you enclose risky code in a try block, you can follow it with multiple catch blocks—each designed to handle a specific type of exception. Java evaluates these catch blocks in order from top to bottom, and executes the first one that matches the thrown exception type.
Think of it like a restaurant with specialized chefs: the try block is the kitchen where things might go wrong, and each catch block is a specialist chef—one handles burnt food, another handles spills, another handles broken equipment. The problem gets routed to the right specialist.
The Syntax
Here's the pattern:
try {
// Code that may throw different types of exceptions
} catch (ExceptionTypeA e) {
// Handle ExceptionTypeA
} catch (ExceptionTypeB e) {
// Handle ExceptionTypeB
} catch (ExceptionTypeC e) {
// Handle ExceptionTypeC
}
Each catch keyword is followed by parentheses containing:
- The exception type (the class name)
- A variable name (often
e, but can be anything)
Example Structure
try {
int result = 10 / 0;
String text = null;
int length = text.length();
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} catch (NullPointerException e) {
System.out.println("Null reference detected");
}
Java checks each catch in sequence. If ArithmeticException is thrown, the first catch executes. If NullPointerException is thrown, the second executes.
Key Takeaway: You can chain multiple catch blocks after a single try block, each targeting a different exception type, allowing you to handle different error scenarios with specialized responses.