In Java, we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to a stack. Given below is an example of a nested try.
In this example, inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block) handles the ArrayIndexOutOfBoundsException.
Example 1:
class NestedTry {
public static void main(String args[])
{
try {
int a[] = { 1 , 2 , 3 , 4 , 5 };
System.out.println(a[ 5 ]);
try {
int x = a[ 2 ] / 0 ;
}
catch (ArithmeticException e2) {
System.out.println( "division by zero is not possible" );
}
}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println( "ArrayIndexOutOfBoundsException" );
System.out.println( "Element at such index does not exists" );
}
}
}
|
Output:
ArrayIndexOutOfBoundsException
Element at such index does not exists
Whenever a try block does not have a catch block for a particular exception, then the catch blocks of parent try block are inspected for that exception, and if a match is found then that catch block is executed.
If none of the catch blocks handles the exception then the Java run-time system will handle the exception and a system generated message would be shown for the exception.
Example 2:
class Nesting {
public static void main(String args[])
{
try {
try {
try {
int arr[] = { 1 , 2 , 3 , 4 };
System.out.println(arr[ 10 ]);
}
catch (ArithmeticException e) {
System.out.println( "Arithmetic exception" );
System.out.println( " try-block1" );
}
}
catch (ArithmeticException e) {
System.out.println( "Arithmetic exception" );
System.out.println( " try-block2" );
}
}
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print( "ArrayIndexOutOfBoundsException" );
System.out.println( " main try-block" );
}
catch (Exception e5) {
System.out.print( "Exception" );
System.out.println( " handled in main try-block" );
}
}
}
|
Output:
ArrayIndexOutOfBoundsException main try-block