How to Handle Multiple Exceptions in Java: Simple Guide
multi-catch block that catches several exceptions in one catch clause separated by a pipe (|), or by writing separate catch blocks for each exception type. This helps keep your code clean and handles different errors properly.Why This Happens
When you try to catch multiple exceptions using a single catch block without proper syntax, Java will give a compile error. This happens because Java expects each catch block to handle one exception type or use the multi-catch syntax introduced in Java 7.
try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println("Caught exception: " + e.getMessage()); } catch (Exception e) { System.out.println("General exception"); } // Incorrect multi-catch example (will cause compile error): // catch (ArithmeticException, ArrayIndexOutOfBoundsException e) { ... }
The Fix
Use the correct multi-catch syntax with a pipe | to catch multiple exceptions in one catch block, or use separate catch blocks for each exception type. This way, Java knows exactly which exceptions you want to handle together.
public class MultipleExceptionsExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); // May throw ArrayIndexOutOfBoundsException int result = 10 / 0; // May throw ArithmeticException } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println("Caught exception: " + e); } } }
Prevention
To avoid errors when handling multiple exceptions, always use the multi-catch syntax with | or separate catch blocks. Keep your exception handling clear and specific. Also, avoid catching overly broad exceptions like Exception unless necessary, to prevent hiding bugs.
Use your IDE's linting tools to warn about incorrect catch syntax and unreachable code. Writing tests that trigger exceptions helps ensure your handlers work as expected.
Related Errors
Common related errors include:
- Unreachable catch block: Happens if a catch block for a superclass exception comes before a subclass exception.
- Incorrect multi-catch syntax: Using commas instead of pipes causes compile errors.
- Swallowed exceptions: Catching exceptions but not handling or logging them can hide problems.