Multiple catch Clauses


In some cases, a single piece of code can raise multiple exceptions. To handle this type of situation, you can specify two or more catch clauses, each with a different type of exception. When an exception is thrown, each catch statement is properly inspected, and the one whose exception is first met is executed. After executing one catch statement, the others are bypassed, and the execution is executed after the try/catch block. The following examples trap two separate exceptions:

Program
public class Main {
  public static void main(String[] args) {
    int a = 12;
    int b = 0;
    try{
     System.out.println("b = " + b);
     int c = a/b;
     int d[]={1,2,3,4};
     System.out.println("d[6] = " + d[6]);
    }
    catch(ArithmeticException ae){
     System.out.println("Divide by 0 : " + ae);
    }
    catch(ArrayIndexOutOfBoundsException aioobe){
     System.out.println("Array index bound : " + aioobe);
    }
    System.out.println("After try/catch blocks.");
  }
}

When you use multiple catch statements, it is important to remember that the exception subclasses must precede any of their superclasses. This is because a catch statement that uses a superclass will capture the exception to any subclass of that kind of a plus. Thus, if a subclass comes after its superclass, it can never be reached. Further, in Java, the access code is an error. For example, consider the following program :

Program
/* This program contains an error.
   A subclass must come before its superclass in
   a series of catch statements. If not,
   unreachable code will be created and a compile-
   time error will result.
*/
public class Main {
  public static void main(String[] args) {
    int a = 12;
    int b = 0;
    try{
     int c = a/b;
    }
    catch(Exception ex){
     System.out.println("Generic Exception catch.");
    }
    /* This catch is never reached because
       ArithmeticException is a subclass of Exception. */
    catch(ArithmeticException ae){ 
     System.out.println("Divide by 0 : " + ae);
    }
    System.out.println("After try/catch blocks.");
  }
}

If you try to compile this program, you will receive an error message stating that the second catch statement is unreachable because the exception has already been caught. Since ArithmeticException is a subclass of Exception, the first catch statement will handle all Exception-based errors, including ArithmeticException. This means that the second catch statement will never execute. To fix the problem, reverse the order of the catch statements.