You are here:   HomeJava ProgrammingException HandlingMultiple Catch Blocks in Java Example
by Dinesh Thakur Category: Exception Handling

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



Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular