Nested Try Catch

Exception thrown in program, pushed on stack for processing. Exception handler pop that exception and process. A try block can contain another try-catch block in it.

Example :


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


Above program having nested try-catch. Outer try has one try-catch inside.



In nested try-catch block if inner try block don't having appropriate catch block then outer catch block also checked against thrown exception.

Example :


class exp
{
public static void main(String arg[])
{ int a[]={12,23,3};
try
{
try
{
System.out.println(a[6]);
}
catch(ArithmeticException ae)
{
System.out.println("Inner Catch Block");
}
}
catch(ArrayIndexOutOfBoundsException a)
{
System.out.println("Outer catch Block");
}
}
}
/* Output:
Outer catch Block
*/


Inner try block has only one catch block for ArithmeticException. If we see the code inner try block is printing value of array at index 6. But the total element in array are 3. Exception will be thrown. ArrayIndexOutOfBoundsException will be pushed on stack and run time will check for handler. First it will check inner catch block, if it won't find matched exception then it will check outer catch block. Outer is matched and Outer catch Block will be printed on screen.