by Dinesh Thakur

Typically, code in a try-block can throw more than one kind of exception. If this is the case then you can put several catch blocks after the try block to handle them, one for each possible exception. When an exception is generated, the JVM searches the catch blocks in order. The first catch block with a parameter that matches the exception thrown will execute, any remaining catch blocks will be skipped.

To illustrate how multiple catch blocks works when an exception occurs, let us consider the following program.

public class MultipleExceptions
{
     public static void main(String[] args)
     {
           int[] num={8,22,16,18,62,52};
           int[] den={2,4,0,6};
           for(int i=0;i<num.length;i++)
               {
                    try
                     {
                           System.out.println(num[i] + "/ " + den[i] +" = "+ num[i]/den[i]);
                     }
                     catch(ArithmeticException e)
                     {
                           System.out.println("Integer Division by 0 not Possible");
                     }
                     catch(ArrayIndexOutOfBoundsException e)
                    {
                           System.out.println("Array Index Out of Bounds");
                    }
               }
       }
}

Multiple Catch Blocks in Java Example