The catch Block: Handling Specific Exception Types
What You'll Learn
You'll learn how catch blocks specify which exception types they handle and execute recovery code when those exceptions occur.
The Core Idea
After marking risky code with a try block, you need a way to respond when something goes wrong. That's where the catch block comes in. Think of it like a safety net designed for specific types of falls—you wouldn't use the same net to catch a baseball as you would to catch a bowling ball.
A catch block declares which exception type it's designed to handle, then provides the recovery code to execute when that exception is thrown.
Basic Syntax
try {
// risky code that may throw an exception
} catch (ExceptionType variableName) {
// recovery code that runs if ExceptionType is thrown
}
The catch block specifies:
- Exception type: What kind of exception it catches (e.g.,
ArithmeticException) - Variable name: A reference to the exception object, so you can access its details
- Recovery code: What to do when this exception occurs
Real Example
try {
int result = 10 / 0; // throws ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
System.out.println("Error details: " + e.getMessage());
}
When division by zero occurs, the JVM throws an ArithmeticException. The catch block that specifies ArithmeticException intercepts it, and the recovery code runs instead of the program crashing.
Key Takeaway: A catch block specifies an exception type and provides recovery code that executes only when that specific type of exception is thrown from the try block.