When a try-catch block is present in another try block then it is called the nested try-catch block. Each time a try block does not have a catch handler for a particular exception, then the catch blocks of the parent try block are inspected for that exception if the match is found that that catch block executes.
Example 1:
public class NestedTryCatchExmple {public static void main(String args[]) {// main try-blocktry {// try-block level 1try {int arr[] = { 1, 2, 3, 4 };// the below statement throws ArrayIndexOutOfBoundsExceptionSystem.out.println(arr[10]);} catch (ArithmeticException e) {System.out.print("Arithmetic Exception");System.out.println(" handled in try-block level 1");}} catch (ArithmeticException e) {System.out.print("Arithmetic Exception");System.out.println(" handled in main try-block");} catch (ArrayIndexOutOfBoundsException e) {System.out.print("ArrayIndexOutOfBoundsException");System.out.println(" handled in main try-block");} catch (Exception e) {System.out.print("Exception");System.out.println(" handled in main try-block");}}}
The above code will throw an ArrayIndexOutOfBoundsException which will be handled in the main try-catch block.
Output
ArrayIndexOutOfBoundsException handled in main try-block
Example 2:
public class NestesTryCatchExamples {public static void main(String args[]) {// Parent try blocktry {// Child try block1try {System.out.println("Inside Child try block1");int b = 45 / 0;System.out.println(b);} catch (ArithmeticException e1) {System.out.println("Exception: e1");}// Child try block2try {System.out.println("Inside Child try block2");int b = 45 / 0;System.out.println(b);} catch (ArrayIndexOutOfBoundsException e2) {System.out.println("Exception: e2");}} catch (ArithmeticException e3) {System.out.println("Arithmetic Exception");System.out.println("Inside parent try catch block");} catch (ArrayIndexOutOfBoundsException e4) {System.out.println("ArrayIndexOutOfBoundsException");System.out.println("Inside parent try catch block");} catch (Exception e5) {System.out.println("Exception");System.out.println("Inside parent try catch block");}}}
Output
Inside Child try block1 Exception: e1 Inside Child try block2 Arithmetic Exception Inside parent try catch block
Exception Handling Using Throw keyword
Exception Handling Using Throws keyword
Java try/ catch block exception handling
Java catch Multiple Exceptions
Java nested try block exception handling
Java custom exception handling
No comments:
Post a Comment