Java Nested try block

In Java, we can use nested try blocks to define exceptions in a hierarchical manner. Using a try block inside another try is permitted. In Java nested try blocks, we can nest one or more try blocks. For example, the inner try block can handle ArrayIndexOutOfBoundsException; on the other hand, the outer try block can handle ArithmeticException(division by zero).

Why do we use nested try in Java?

  • Nested try block is used when different blocks, like inner try block and outer try block, may cause different types of errors.
  • To handle them, we need to use nested try blocks.

Syntax

try {
   statement 1;
   statement 2;
 
   try {
      statement 3;
      statement 4;
    
      try {
         statement 5;
         statement 6;
      }
      catch(Exception e2) {
         //Exception Message
      }
   }
   catch(Exception e1) {
       //Exception Message
   }
   
}

catch(Exception e3) {
      //Exception Message
}

nested try

Example

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

            
            int a[] = {1,2, 3, 4, 5 };rrayIndexOutOfBoundsException
ElSystem.out.println(a[5]);
            try {
int x = a[2] / 0;
            }
            catch (ArithmeticException e2) {
                System.out.println("division by zero is not possible");
            }
        }
        catch (ArrayIndexOutOfBoundsException e1) {
            System.out.println("ArrayIndexOutOfBoundsException");
            System.out.println("Element at such index does not exists");
        }
    }
}

Output

ArrayIndexOutOfBoundsException
Element at such index does not exist

Conclusion

However, it’s essential to maintain a balance between the depth of nesting and code readability. Overly complex nesting can lead to confusion and hinder the understanding of the code logic. Therefore, it’s recommended to use nested try blocks judiciously and consider alternatives like extracting code into separate methods or classes when appropriate.