Java nested try blocks

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner block does not catch an exception, it is passed on to the outer try block. Here, the outer catch block will handle this exception. This continues until one of the catch statements succeeds, or until the entire nested try statements are exhausted. If no catch statement matches, then the Java runtime system will handle the exception. See the following program (Except05.java).

public class Except05 {

public static void main(String[] args) {
int a = 10;
int b = 0;
int arr[] = new int[10];
String str = null;
double n = Math.random();

//outer try
try {
if (n < 0.3) {
int c = a / b;
}
//inner try
try {
if (n < 0.6) {
arr[20] = 100;
}
else {
char ch = str.charAt(0);
}
} //end of inner try

catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception : " + e);
}

} //end of outer try

catch (ArithmeticException e) {
System.out.println("Exception : " + e);
}

catch (NullPointerException e) {
System.out.println("Exception : " + e);
}

} //end of main()

} //end of class

 

The output will vary depending on the value of ‘n’ as usual.