Java Multiple Exceptions
While writing Java programs, it is common for different types of exceptions to occur within the same block of code. For example, a program might encounter an array access error, a division error, or an invalid input issue.
Java allows developers to manage these situations effectively by using multiple catch blocks or a multi-catch statement. This ensures that each exception type can be handled appropriately without crashing the application.
This guide explains how to handle multiple exceptions in Java, why the order of catch blocks matters, and how to simplify exception handling using multi-catch (Java 7+).
Handling Multiple Exceptions with Multiple Catch Blocks
A single try block can be followed by multiple catch blocks, each designed to handle a specific type of exception.
When an exception occurs, Java searches the catch blocks from top to bottom and executes the first matching catch block.
Syntax
try {
// Code that might throw exceptions
}
catch (ExceptionType1 e) {
// Handle exception type 1
}
catch (ExceptionType2 e) {
// Handle exception type 2
}
Example: Handling Multiple Exception Types
The following program demonstrates how different exceptions can be handled separately.
public class MultipleExceptionDemo {
public static void main(String[] args) {
try {
int[] data = {5, 10, 15};
System.out.println("Accessing array element...");
System.out.println(data[6]); // Invalid index
int value = 50 / 0; // Division error
System.out.println(value);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access an index outside the array.");
}
catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
catch (Exception e) {
System.out.println("An unexpected error occurred.");
}
}
}
Output
Accessing array element...
Error: Attempted to access an index outside the array.
Explanation
Even though two possible errors exist in the code:
- Invalid array index
- Division by zero
Only the first error encountered is thrown. Therefore, Java executes the corresponding catch block and stops checking the rest.
Why the Order of Catch Blocks Matters
When handling multiple exceptions, the order of catch blocks is very important.
Java requires that more specific exceptions appear before more general ones. If a general exception like Exception is placed first, it will catch all errors, making the specific catch blocks unreachable
Incorrect Order (Bad Practice)
try {
int result = 40 / 0;
}
catch (Exception e) {
System.out.println("A general exception occurred.");
}
catch (ArithmeticException e) {
System.out.println("Division by zero error.");
}
In this case:
The Exception block catches all exceptions, including ArithmeticException.
Therefore, the second catch block will never execute, resulting in a compilation error.
Correct Order (Best Practice)
try {
int result = 40 / 0;
}
catch (ArithmeticException e) {
System.out.println("Division by zero error.");
}
catch (Exception e) {
System.out.println("General exception occurred.");
}
Tip: Always place specific exceptions first and general exceptions last.
Multi-Catch in Java (Java 7 and Later)
Starting from Java 7, developers can catch multiple exception types within a single catch block using the pipe (|) operator.
This approach is useful when different exceptions require the same handling logic.
Syntax
catch (ExceptionType1 | ExceptionType2 e) {
// Shared handling logic
}
Example: Using Multi-Catch
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] marks = {80, 75, 90};
int score = marks[4]; // Array index error
int average = score / 0; // Arithmetic error
System.out.println(average);
}
catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("A mathematical or array access error occurred.");
}
}
}
Output
A mathematical or array access error occurred.
Explanation
Here, both ArithmeticException and ArrayIndexOutOfBoundsException are handled by the
same catch block, avoiding duplicate code.