What is nested try-catch block?
Nested try-catch block means a try-catch block containing another try-catch block. In some cases, part of a block can cause one error and the entire block can cause another. In such cases, Java allows us to enclose a try catch in another try catch block which is known as nested try-catch block.
Syntax
try { Statement 1 Statement 2 Statement 3 // A nested try catch block try { // Body of nested try block. } catch(<exception_class> <object_name>) { // Body of nested catch block. } Statement N } catch (<exception_class> <object_name>) { // Body of parent catch block. }
Example 1
In the following example program, one nested try-catch block is created to handle unexpected null pointer exception and the outer exception can handle any type of checked/unchecked exceptions.
public class NestedTryCatchExample1 { public static void main(String[] args) { try { String str = null; int length = 0; try { length = str.length(); } catch (NullPointerException ex) { // Handle the nested exception here. System.out.println("Oops string is not looking good!"); } System.out.println("Length of a string: " + length); } catch (Exception ex) { // Handle any type of exception here. System.out.println("Unknown exception!"); } } }
Example 2
The following program is just similar to the above one, but here nested try-catch block is not capable to handle the exception so it is passing the exception to the parent catch block.
public class NestedTryCatchExample2 { public static void main(String[] args) { try { int numA = 1000; int numB = 0; int result = 0; // It can only handle null pointer exception try { // Divide a number by zero. result = numA / numB; } catch (NullPointerException ex) { // Handle the nested exception here. System.out.println(ex); } System.out.println("Result is: " + result); } catch (Exception ex) { // Handle any type of exception here. System.out.println("Unknown exception!"); } } }