Nested try blocks in Exception Handling in Java

Java 8Object Oriented ProgrammingProgramming

As the name suggests, a try block within a try block is called nested try block in Java. This is needed when different blocks like outer and inner may cause different errors. To handle them, we need nested try blocks.

Let us now see an example to implement nested try blocks −

Example

class Main {
   // main method
   public static void main(String args[]) {
      try {
         int a[]=new int[10];
         // displaying element at index 12
         System.out.println(a[12]);
         // another try block
         try {
            System.out.println("Division");
            int res = 100/ 0;
         }
         catch (ArithmeticException ex2) {
            System.out.println("Sorry! Division by zero isn't feasible!");
         }
      }
      catch (ArrayIndexOutOfBoundsException ex1) {
         System.out.println("ArrayIndexOutOfBoundsException");
      }
   }
}

Output

ArrayIndexOutOfBoundsException

Now we will do some changes in the above example −

Example

class Main {
   // main method
   public static void main(String args[]) {
      try {
         int a[] = {30, 45, 60, 75, 90, 105, 120, 140, 160, 200};
         // displaying element at index 8
         System.out.println("Element at index 8 = "+a[8]);
         // another try block
         try {
            System.out.println("Division");
            int res = 100/ 0;
         }
         catch (ArithmeticException ex2) {
            System.out.println("Sorry! Division by zero isn't feasible!");
         }
      }
      catch (ArrayIndexOutOfBoundsException ex1) {
         System.out.println("ArrayIndexOutOfBoundsException");
      }
   }
}

Output

Element at index 8 = 160
Division
Sorry! Division by zero isn't feasible!
raja
Published on 20-Sep-2019 11:13:20
Advertisements