Skip to content

Multiple Catch

In Java, the Multiple Catch mechanism allows you to handle different exceptions that might be thrown by a try block using multiple catch blocks. Each catch block is used to handle a specific type of exception. This feature makes the code more robust and improves readability by allowing customized handling of various exception types.


Syntax

try {

    // Code that may throw exceptions

} catch (ExceptionType1 e1) {

    // Handle ExceptionType1

} catch (ExceptionType2 e2) {

    // Handle ExceptionType2

} catch (ExceptionType3 e3) {

    // Handle ExceptionType3

}


Key Points

  1. Order Matters:
    1. Catch blocks should be ordered from the most specific exception type to the most general (Exception).
    1. If a more general catch block is placed before a specific one, a compile-time error will occur.
  2. Exclusive Execution:
    1. Only one catch block is executed. When an exception is caught, the remaining catch blocks are skipped.
  3. Unrelated Exceptions:
    1. Multiple catch blocks allow handling unrelated exceptions separately.

Example: Multiple Catch Blocks

public class MultipleCatchExample {

    public static void main(String[] args) {

        try {

            int[] numbers = {1, 2, 3};

            int result = numbers[1] / 0; // ArithmeticException

            System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException

        } catch (ArithmeticException e) {

            System.out.println(“Arithmetic error: Cannot divide by zero.”);

        } catch (ArrayIndexOutOfBoundsException e) {

            System.out.println(“Array index out of bounds.”);

        } catch (Exception e) {

            System.out.println(“Some other exception occurred.”);

        }

    }

}

Output:

Arithmetic error: Cannot divide by zero.


Combining Multiple Exceptions (Java 7 and Later)

Java 7 introduced the multi-catch feature, which allows multiple exceptions to be caught in a single catch block using the pipe (|) operator. This reduces code duplication.

Syntax

try {

    // Code that may throw exceptions

} catch (ExceptionType1 | ExceptionType2 e) {

    // Handle both ExceptionType1 and ExceptionType2

}

Example

public class MultiCatchExample {

    public static void main(String[] args) {

        try {

            String str = null;

            System.out.println(str.length()); // NullPointerException

        } catch (NullPointerException | ArithmeticException e) {

            System.out.println(“Caught a NullPointerException or ArithmeticException.”);

        }

    }

}

Output:

Caught a NullPointerException or ArithmeticException.


Multiple Catch vs Multi-Catch

FeatureMultiple CatchMulti-Catch
Separate HandlingEach catch block has unique handling logic.Single block handles multiple exceptions similarly.
Code DuplicationRepeated logic if handling is similar.Reduces duplication by combining exceptions.
FlexibilityGreater flexibility for custom handling.Suitable for exceptions with identical handling.

Best Practices for Using Multiple Catch

  1. Use Specific Exceptions First:
    1. Place specific exception types before generic ones like Exception.
  2. Avoid Catching Throwable:
    1. Do not catch Throwable or Error unless absolutely necessary.
  3. Multi-Catch for Similar Handling:
    1. Use multi-catch for exceptions requiring the same handling logic.
  4. Always Log Exceptions:
    1. Include meaningful logs for debugging and maintenance.
  5. Don’t Overuse Multiple Catch:
    1. Simplify exception handling where possible by refactoring.

Conclusion Multiple catch blocks provide a structured and clean way to handle different exceptions separately in Java. With the introduction of multi-catch, developers can reduce code redundancy while maintaining functionality. Proper use of these features ensures robust and maintainable error-handling logic.