← Back to Chapters

Java Multiple Catch Blocks

☕ Java Multiple Catch Blocks

? Quick Overview

In Java, multiple catch blocks allow you to handle different types of exceptions separately within a single try block. This improves error handling clarity and prevents application crashes.

? Key Concepts

  • Multiple exceptions can occur in one try block
  • Each exception can be handled with its own catch
  • More specific exceptions must come before generic ones
  • Improves readability and debugging

? Syntax / Theory

Java allows more than one catch block after a single try. The JVM matches the thrown exception with the first compatible catch block.

? View Code Example
// Syntax of multiple catch blocks in Java
try {
    // code that may throw exceptions
} catch (ExceptionType1 e) {
    // handle exception type 1
} catch (ExceptionType2 e) {
    // handle exception type 2
}

? Code Example

? View Code Example
// Demonstrating multiple catch blocks
public class MultipleCatchDemo {
    public static void main(String[] args) {
        try {
            int[] numbers = {10, 20, 30};
            System.out.println(numbers[5]);
            int result = 10 / 0;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index error occurred");
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error occurred");
        }
    }
}

? Live Output / Explanation

Output

Array index error occurred

The program throws an ArrayIndexOutOfBoundsException first, so the corresponding catch block executes. Remaining code is skipped.

? Interactive Simulation

The array is {10, 20, 30} (Valid indexes: 0, 1, 2).
Change values to see which block catches the error!

try {
  int n = numbers[index];
  int r = n / divisor;
}
catch (ArrayIndexOutOfBoundsException) {
  print("Index Error!");
}
catch (ArithmeticException) {
  print("Can't divide by zero!");
}
// Success (No Exception)
  Code execution continues...
 

✅ Tips & Best Practices

  • Always catch specific exceptions before general ones
  • Avoid using only Exception as a catch-all
  • Keep catch blocks short and meaningful
  • Use multiple catch to improve debugging

? Try It Yourself

  • Add a NullPointerException catch block
  • Reorder catch blocks and observe compiler errors
  • Replace multiple catch with multi-catch syntax