Wednesday, 22 January 2014

NESTED try STATEMENT

NESTED try IN EXCEPTION HANDLING


Java:nested try-catch blocks with simple example

The try block within a try block is known as 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 using nested 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 general form is as shown below:

....  
try  
{  
    statement 1;  
    statement 2;  
    try  
    {  
        statement 1;  
        statement 2;  
    }  
    catch(Exception1 e)  
    { 
  //statements to handle the exception
    }  
}  
catch(Exception2 e)  
{  
//statements to handle the exception
}  
....  

Example for nested try Statements:

import java.io.*;
public class NestedTry
{
  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:
Array index is Out of bound! Argument required.


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. Now lets see, what will be the output if we pass the file name student as an argument.


Output:
student.txt
File not found!

If the outer try block’s statements run successfully then the inner try will raise an ArithmeticException as:

Output:
student.txt
divided by zero

No comments:

Post a Comment