Nested try catch block Handling

In Java we can have nested try and catch blocks. It means that, a try statement can be inside the block of another try. 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?s 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 in. If no one catch statements match, then the Java run-time system will handle the exception.

Why use nested try block?
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested, one within another. In java, this can be done usingnested try blocks. A try statement can be inside the block of another try. In a nested try block, every time a try block is entered the context of that exception is pushed on the stack.

The following code snippet explains the syntax of a nested try…catch block.

Syntax:

....
try
{
    statement 1;
    statement 2;
    try
    {
        statement 1;
        statement 2;
    }
    catch(Exception e)
    {
    }
}
catch(Exception e)
{
}
....

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.

Lets have an example that uses the nested try-catch blocks.

import java.io.*;
public class NestedTryCatchBlock{
  public static void main (String args[])throws IOException  {
  int num=2,res=0;
  
  try{
  FileInputStream fis=null;
  fis = new FileInputStream (new File (args[0]));
  try{
  res=num/0;
  System.out.println("The result is"+res);
  }
  catch(ArithmeticException e){
  System.out.println("divided by Zero");
  }
  }
  catch (FileNotFoundException e){
  System.out.println("File not found!");
  }
  catch(ArrayIndexOutOfBoundsException e){
  System.out.println("Array index is Out of bound! Argument required");
  }
  catch(Exception e){
  System.out.println("Error.."+e);
  }
}
}

Output of the program:

Nested try catch block Handling

In this given example we have implemented nested try-catch blocks concept where an inner try block is kept with in an outer try block, that’s catch handler will handle the arithmetic exception. But before that an ArrayIndexOutOfBoundsException will be raised, if a file name is not passed as an argument while running the program.

<<Previous <<   || Index ||   >>Next >>
Previous
Next