Java Exception multiple catch clauses

Introduction

To handle more than one exception types:

// Demonstrate multiple catch statements.  
public class Main {
  public static void main(String args[]) {
    try {//  w  w w. j  av  a 2  s  . c om
      int a = 0;
      System.out.println("a = " + a);
      int b = 42 / a;
      int[] c = { 1 };
      c[2] = 99;
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index oob: " + e);
    }
    System.out.println("After try/catch blocks.");
  }
}

When using multiple catch statements, exception subclasses must come before any of their super classes.

A catch statement with a superclass will catch exceptions of that type plus any of its sub classes.




PreviousNext

Related