Catching multiple exceptions

In Java, catching multiple exceptions allows you to handle different types of exceptions in a more concise and efficient way, especially when the handling logic for those exceptions is the same. Prior to Java 7, you would need to write separate catch blocks for each exception type. But with Java 7 and onwards, you can catch multiple exceptions in a single catch block by using the pipe (|) symbol to separate the exceptions.

  • Multiple Exception Types in One Catch Block: You can specify multiple exception types in a single catch block, making your code cleaner and reducing redundancy.

  • Common Handling Logic: This approach is typically used when the handling logic for all the specified exceptions is the same.

  • Order of Exceptions: Java evaluates the exceptions from left to right, so if a parent exception type is listed before its child type, the child exception will never be caught. For example, Exception | IOException would cause a compilation error because IOException is a subclass of Exception.

Syntax

try {
    // Code that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 | ExceptionType3 e) {
    // Handle the exceptions
}Code language: JavaScript (javascript)

Program

public class MultipleExceptionCatchExample {
    public static void main(String[] args) {
        try {
            String str = null;
            // This will throw a NullPointerException
            System.out.println(str.length());

            int[] arr = new int[5];
            // This will throw an ArrayIndexOutOfBoundsException
            System.out.println(arr[10]);

        } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
            // Handling both exceptions in the same catch block
            System.out.println("Caught an exception: " + e);
        }
    }
}
/*
Caught an exception: java.lang.NullPointerException
*/

Advantages:

  • Improved Readability: Reduces the need for multiple catch blocks if exceptions require similar handling.

  • Cleaner Code: Reduces redundancy and improves the maintenance of code.

Catching multiple exceptions in a single catch block simplifies the handling of different exceptions that require similar handling logic. This feature, introduced in Java 7, enhances the readability and maintainability of the code, especially in situations where several exceptions need the same resolution steps. However, it’s important to use it with care to avoid catching broader exceptions that could obscure specific error conditions

Scroll to Top