Can we declare a try catch block within another try catch block in Java?


Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

Nested Try-Catch Block

  • If an inner try statement does not have a matching catch statement for a particular exception, the control is transferred to the next try statement catch handlers that are expected for a matching catch statement.
  • This continues until one of the catch statements succeeds, or until all of the nested try statements are done.
  • If no one catch statements match, then the Java run-time system will handle the exception.
  • When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try block are inspected until all nested try statements are exhausted. If no matching blocks are found, the Java Runtime Environment handles the execution.

Syntax

try {
   statement 1;
   statement 2;
   try {
      statement 1;
      statement 2;
   }
   catch(Exception e) {
      // catch the corresponding exception  
   }  
}
catch(Exception e) {
   // catch the corresponding exception
}
   .............

Example

Live Demo

import java.io.*;
public class NestedTryCatchTest {
   public static void main (String args[]) throws IOException {
    int n = 10, result = 0;
      try { // outer try block
         FileInputStream fis = null;
         fis = new FileInputStream (new File (args[0]));
         try { // inner trty block
            result = n/0;
            System.out.println("The result is"+result);
         }  
         catch(ArithmeticException e) { // inner catch block
            System.out.println("Division by Zero");
         }
      }
      catch (FileNotFoundException e) { // outer catch block
         System.out.println("File was not found");
      }
      catch(ArrayIndexOutOfBoundsException e) { // outer catch block
         System.out.println("Array Index Out Of Bounds Exception occured ");
      }
      catch(Exception e) { // outer catch block
         System.out.println("Exception occured"+e);
      }
   }
}

Output

Array Index Out Of Bounds Exception occured

Updated on: 30-Jul-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements