Nested try Blocks
Sometimes, we need to nest one try block into another. This maybe because some piece of code might throw one exception and some of the lines within the outer try block may throw another exception.
Syntax of nested try blocks
try {
//code line1
//code line2
try {
//code line3
try {
//code line4
} catch (IOException e) {
//exception handling code
}
} catch (IOException e) {
//exception handling code
}
//code line5
} catch (ArrayIndexOutOfBoundsException e) {
//exception handling code
}
Nested try example 1
In the below example, we have nested try blocks. In the first scenario, exception occurs in the outer try block and thus the program control doesn’t go in the nested try block. Let’s see
package com.javatrainingschool;
public class NestedTryExample {
public static void main (String [] args) {
int num1 = 15;
int num2 = 0;
int result = 0;
int arr [] = new int [] {11, 12, 13, 14, 15, 16};
try {
result = num1 / num2;
int value = 0;
try {
value = arr [result];
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
System.out.println("Array value = " + value);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
Output :
java.lang.ArithmeticException: / by zero
at com.javatrainingschool.NestedTryExample.main(NestedTryExample.java:13)
Nested try example 2
In the below example, which is almost same as the above one, we have fixed the exception in the outer try block. It doesn’t occur now. That’s why we get the desired result. Let’s see
package com.javatrainingschool;
public class NestedTryExample {
public static void main (String [] args) {
int num1 = 15;
int num2 = 3;
int result = 0;
int arr [] = new int [] {11, 12, 13, 14, 15, 16};
try {
result = num1 / num2;
int value = 0;
try {
value = arr [result];
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
System.out.println("Array value = " + value);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
Output :
Array value = 16
Nested try example 3
Below example is also almost same as the above two. The only difference here is that now exception occurs in the nested try block. But we have handled it using catch block. Let’s understand the same
package com.javatrainingschool;
public class NestedTryExample {
public static void main (String [] args) {
int num1 = 15;
int num2 = 3;
int result = 0;
int arr [] = new int [] {11, 12, 13, 14, 15};
try {
result = num1 / num2;
int value = 0;
try {
value = arr [result];
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
System.out.println("Array value = " + value);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
Output :
java.lang.ArrayIndexOutOfBoundsException: 5
at com.javatrainingschool.NestedTryExample.main(NestedTryExample.java:16)
Array value = 0