Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Multi‑Exception Handling in Java

Mastering Multi‑Exception Handling in Java

Discover how to catch several exceptions with a single catch block, streamline your code, and avoid common pitfalls.

Before Java 7, developers had to write separate catch blocks for each exception type, even when the handling logic was identical.

Consider the following scenario.

Example 1: Separate catch blocks

class Main {
    public static void main(String[] args) {
        try {
            int[] array = new int[10];
            array[10] = 30 / 0;
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

/ by zero

In this example two distinct problems can arise:

Both catch blocks perform the same action, leading to duplicated code.


Catching Multiple Exceptions in a Single Block

Since Java SE 7, you can combine several exception types into one catch block using the pipe (|) separator.

Syntax:

try {
    // code
} catch (ExceptionType1 | ExceptionType2 ex) {
    // handler
}

Example 2: Multi‑catch block

class Main {
    public static void main(String[] args) {
        try {
            int[] array = new int[10];
            array[10] = 30 / 0;
        } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

/ by zero

By merging the handlers, the code is cleaner, the bytecode smaller, and maintenance easier.

Note: In a multi‑catch, the parameter is implicitly final, so you cannot reassign it.


Using a Base Exception Class

If several caught exceptions share a common ancestor, you can catch that ancestor instead of listing each subclass.

Example 3: Catching the base Exception class

class Main {
    public static void main(String[] args) {
        try {
            int[] array = new int[10];
            array[10] = 30 / 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

/ by zero

Because every specific exception in Java extends Exception, this single catch block handles all the scenarios above.


If a base exception is already caught, including its subclasses in the same catch will trigger a compilation error.

Example 4: Invalid combination of base and child exceptions

class Main {
    public static void main(String[] args) {
        try {
            int[] array = new int[10];
            array[10] = 30 / 0;
        } catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassing

This error occurs because ArithmeticException and ArrayIndexOutOfBoundsException are subclasses of Exception, violating the language rule.


Java

  1. Master Java Operators: Types, Syntax, & Practical Examples
  2. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  3. Mastering Java Interfaces: Concepts, Implementation, and Best Practices
  4. Java Exceptions: Types, Hierarchy & Handling
  5. Mastering Java Exception Handling: Try, Catch, Finally, and Resources
  6. Java throw vs throws: Mastering Exception Handling with Practical Examples
  7. Mastering Java Try‑with‑Resources: Automatic Resource Management Explained
  8. Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained
  9. Avoiding Common Pitfalls: Proper Exception Handling in Python
  10. Mastering Java Exceptions: Handling Unexpected Errors Gracefully