Multiple try-Catch

One try block can have multiple catch clauses. At the time, exception is thrown run time will check exception type with every catch clause's exception. Catch clause with match will be executed.


Syntax :

try 
{
< code that can generate exception >
}
catch(<type of exception> e)
{
< code which will be executed when exception occurred >
}
catch(<type of exception> e)
{
< code which will be executed when exception occurred >
}
catch(<type of exception> e)
{
< code which will be executed when exception occurred >
}
catch(<type of exception> e)
{
< code which will be executed when exception occurred >
}

Program with multiple catch


 class exp
{
public static void main(String arg[])
{
try
{
int b=Integer.parseInt(arg[0]);
int a=4/;
System.out.println("a:"+a);
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println(a);
}
System.out.println("End of program");
}
}


Above program having two catch block one for ArithmeticException and another for ArrayIndexOutOfBoundsException .


  c:\>java exp 
java.lang.ArrayIndexOutOfBoundsException:0
End of program


When above program is executed without any command line argument then int b=Integer.parseInt(arg[0]) statement will cause ArrayIndexOutOfBoundsException . Second catch block will be executed then. Now if command line argument 0 given by user then int a=4/b; will cause ArithmeticException and first catch block will get executed.


Execution :

   c:\>java exp 0 
java.lang.ArithmeticException:/ by Zero
End of program
Note ! All the subclass exception should be specified first then super class exception.

Example :


class exp 
{
public static void main(String arg[])
{
try
{
int b=Integer.parseInt(arg[0]);
int a=4/b;
System.out.println("a:"+a);
}
catch(Exception e)
{
System.out.println("Exception catch");
}
catch(ArithmeticException ae)
{
System.out.println("Divide by zero catch");
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println("Array Exception");
}
System.out.println("End of program");
}
}

In above program if any exception will be thrown first catch block will execute always. Reason: Exception is super class of all exception. In multiple catch block structure, sub class exception should be caught first and super class exception lated.


Correct code for above is:


class exp
{
public static void main(String arg[])
{
try
{
int b=Integer.parseInt(arg[0]);
int a=4/b;
System.out.println("a:"+a);
}

catch(ArithmeticException ae)
{
System.out.println("Divide by zero catch");
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println("Array Exception");
}
catch(Exception e)
{
System.out.println("Exception catch");
}
System.out.println("End of program");
}
}