Nested try-catch block

Nested try-catch block

try-catch block within the other try-catch block is called nested-try catch block.

When a part of block cause one exception and the entire block causes another exception, in this scenario we should use nested Try-catch blocks. In case if the inner try block doesn’t have a catch block then the outer catch block can be used to check for the exception

Syntax

//Main try block
try {
statement 1;
statement 2;
//try-catch block within the another try block
try {
statement 3;
statement 4;
//try-catch block within the nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}
}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}

Example

class main
{
public static void main(String[] args)
{
try
{
int arr[]={8,6,0,7};
try
{
int x = arr[0]/arr[2];
}
catch(ArithmeticException e)
{
System.out.println("divided by zero");
}
arr[8]=11;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
catch(Exception e)
{
System.out.println("All exceptions are Catched");
}
}
}

Output

divided by zero
array index out of bound exception

In the above program, there is the main try-catch block and inside it, another try-catch block is there, if any exception occurs for the inner try block then, if it has a suitable catch block then the exception is handled. From the above example “divide by zero exception is handled” , if the same inner catch block has different exception type,then control gets transferred to the outer main catch block to check the suitable catch handler

in the first try block, there is a statement arr[8]=11; now the exception occurs, controller checks for the suitable exception handler for the exception, in the example it is handled by ArrayIndexOutOfBoundsException

If there is an inner try block or any other try block, the when the exception occurs, controller checks for the suitable catch handler in its own catch block, and the other outer blocks to, at last as mentioned in our program last is the generic catch block, so every exception can be handled at the generic catch block

Last updated on by vishal devxo