Login    New User    Forgot Password    Help      

Multiple Catch Blocks

Java Tutorials

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

 

Syntax


try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.

 

Example

// Multiple catch clauses
// Run with argument 0,1,2;

 

class ex
{
int m;
        void div(int n)
        {
        // monitor block of code
        try
                {
                n--;
                m=m/n;
                // this will not print on the time of divide by o
                System.out.println("Divide  "+ ++n +" by " + --n +" == " + m);

               
                int c[]={1};
                c[1]=99;
                }

       
catch (ArithmeticException e)
                {
                System.out.println("Divide by zero is Not possible");
                // use following statement to see the error
                //System.out.println(e);
                }
       
catch (ArrayIndexOutOfBoundsException e)
                {
                System.out.println("Array index obb : ");
                }
       
    
  }
}
 

class  ex2
{
public static void main(String args[])
{
int n;

n=Integer.parseInt(args[0]);
ex ob1=new ex();
ob1.div(n);

}
}

 

Output

 

Java Tutorials