Multiple Catch- Exception

So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.In Java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program i.e. you can use more than one catch clause in a single try block however every catch block can handle only one type of exception. this mechanism is necessary when the try block has statement that raise  different type of exceptions.
The syntax for using this clause is given below:-



catch(Exception e1){


catch(Exception e2){


when an exception occurs normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If first one catch block has not matched then the second one is matched and so on....


class DivByZero {
public static void main(String args[]) {

System.out.println(3/0);    //here arithmetic exception has come

System.out.println(“Pls. print me.”);

}catch( ArrayIndexOutOfBoundsException e){

 System.out.println(“Exception 1.”); 


catch(ArithmeticException e1){

System.out.println(“Exception e2”);





In this example we have used two catch clause catching the exception ArrayIndexOutOfBoundsException and  Arithmetic Exception in which the statements that may raise exception are kept under the try block. When the program is executed, an exception will be raised. Now that time  the first catch block is skipped and the second catch block handles the error.

People who read this post also read :


Post a Comment


Twitter Delicious Facebook Digg Stumbleupon Favorites More