Multiple catch blocks

In Java, a try block can be followed by multiple catch blocks, allowing you to handle different types of exceptions separately. This structure helps make your exception handling more robust and fine-grained.

Syntax

try {
    // Code that might throw multiple exceptions
} catch (ArithmeticException e) {
    // Handle arithmetic exception
} catch (NullPointerException e) {
    // Handle null pointer exception
} catch (Exception e) {
    // Handle any other exceptions
}Code language: PHP (php)

Important Rules

  1. Order matters: Always catch the more specific exceptions before the more general ones. If you catch a superclass (like Exception) before its subclass, the compiler will throw an error.

  2. Only one catch block executes: Once a matching catch block is found and executed, others are skipped.

  3. Use multi-catch (|) for similar handling.

Program

public class MultipleCatchExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            int result = numbers[3] / 0;  // Throws ArrayIndexOutOfBoundsException first
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception caught: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array Index Exception caught: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("General Exception caught: " + e.getMessage());
        }
    }
}
/*
Array Index Exception caught: Index 3 out of bounds for length 3
*/

In above program, Even though there’s a divide by zero (/ 0), the array index exception occurs first and is handled.

Multi-Catch Example

Use multi-catch only if you handle both exceptions in the same way.

try {
    // risky code
} catch (IOException | SQLException e) {
    // Same handling logic for both
    e.printStackTrace();
}Code language: JavaScript (javascript)

Multiple catch blocks provide a structured way to handle different types of exceptions that may arise within a single try block. By catching specific exceptions individually, Java allows developers to write precise and meaningful error-handling logic, improving code reliability and maintainability. Proper ordering—from most specific to most general—is essential to prevent unreachable code errors. Additionally, the multi-catch feature (using |) simplifies scenarios where different exceptions require the same handling. Overall, using multiple catch blocks enhances the robustness of applications by addressing diverse error conditions explicitly and effectively.

Scroll to Top