Multiple Catch Blocks
Sometimes a block of code can generate more than one type of
exception. Java allowing you to use multiple catch blocks to handle
different errors differently.
Syntax
try {
// Block of code
}
catch(ArithmeticException e) {
// Handle Math errors
}
catch(ArrayIndexOutOfBoundsException e) {
// Handle Array errors
}
catch(Exception e) {
// Handle everything else
}
The Golden Rule: Order Matters
Important: You must catch the most specific
exceptions first and the most general (Exception) last.
If you put catch(Exception e) first, it will catch
everything, and the specific blocks below it will never be reached
(causing a compile error).
Example
Let's try to perform an operation that could fail in two ways: dividing by zero OR accessing a bad index.
Output
Click Run to execute your code
Summary
- Use multiple catch blocks to handle different errors specifically.
- Order them from specific (child classes) to general (parent classes).
- Only one catch block will be executed.
Enjoying these tutorials?