Uttar Pradesh, India
Instagram
image

Flow control in Nested try catch

To the smooth execution of the program, Nested try-catch blocks are a very essential requirement in programming practice. There are multiple try-catch blocks are possible inside the single try block. This configuration is known as Nested try catch.

Why use a nested try block

Many times a situation may arise where a first statement throws one type of  exception and second statement  throws different type of exception.So such kinds of situation  may be possible to remaining a group of statements .In order to handle such cases, exception handlers have to be nested.

Demo program describes clearly.

Demo Program:

package com.navneet.javatutorial;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Nestedtrycatch {
public static void main(String args[]) {

try {
System.out.println("Statement 1");                              // Statement1
System.out.println("Statement 2" + 10 / 0);              // Having exception in Statement2

}

catch (ArithmeticException e1) {
System.out.println("Statement 3" + 10 / 5);               // Handling code for statement2
PrintWriter pw = null;
try {
pw = new PrintWriter("D:\Nestedtrycatchdemo.txt");                      

                                                  // May be possible  FileNotFoundException in  Statement4
pw.write("Nested try catch demo");
pw.flush();
}

catch (FileNotFoundException e2) {
System.out.println("Hello");
}

finally {
pw.close();
try {
int[] array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = 2;
array[3] = 2;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);                                        // Having exception in Statement 5

}
} catch (ArrayIndexOutOfBoundsException e3) {

}
System.out.println("The sub final block inside catch");
}
}

finally {
System.out.println("The main final block");

          }

     }

}

Syntax structure of Nested try catch is given below.


Comments

Share your thoughts in the comments

Your email address will not be published. Required fields are marked *