How to handle multiple exception together?
- We can write multiple catch block and each catch block for one exception or you can write single catch block with multiple exception and separate exception by pipe symbol
- When we write multiple catch block, we must follow bellow rules:
Handle the most specific exception at the first and move down for the most generic exception
Example:
public class MultiCatchExample {
public static void main(String[] args) {
try {
// Code that might throw exceptions
int[] numbers = {10, 20};
int result = numbers[2] / 0; // This will throw ArrayIndexOutOfBoundsException and ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
// Handle ArrayIndexOutOfBoundsException
System.out.println(“Error: Array index is out of bounds.”);
} catch (ArithmeticException e) {
// Handle ArithmeticException
System.out.println(“Error: Division by zero is not allowed.”);
} catch (Exception e) {
// Handle any other exceptions
System.out.println(“An unexpected error occurred: ” + e.getMessage());
}
System.out.println(“Program continues normally…”);
}
}