Java exception handling Nestd try

The try statement can be can be nested.That is a try statement can be inside the block of another try .Each time a try statement is enters the context of that exception is pushed on the stack .if an inner try statement does not have a catch handler for a particular exception ,the stack is unwound and the next try statements catch handlers are inspected for a match.This continues until one of the catch statements succeeds or until all of the nested try statements are exhausted .if no catch statement matches ,then the java run-time system will handle the exception.Here is an example that uses nested try statements


class Nesttry
{
    public static void main(String arg[])
    {
           try
        {      
           int a=arg.length;
          int b=42/a;
          System.out.println("a= "+a);
          try
            {
            if(a==1)
            a=a/(a-a);
            if(a==2)
                {
                int c[]={1};
                c[42]=99;
                }
            }
         catch(ArrayIndexOutOfBoundsException ae)
            {
            System.out.println("Array index out out of bounds :"+ae);
            }
        }
         catch(ArithmeticException e)
            {
            System.out.println("Divide by 0:"+e);
            }
        }
}

as you can see this program nests one try block with in another .The program works as follows .When you execute the program with mo command line arguments a didivde by zero exception is generated by the outer try  block .Exception of the program by one command line argument generates a divide-by Zero exception from within the nested try block,Since the inner block does not catch this exception it is passed on to the outer try block ,Where it is handled .if you execute the program with two command line arguments an array boundary exception is generated from within the inner try block .

Output


C:\>Javac Nesttry.java
C:\>Java Nesttry
Divide by 0:java.lang.ArithmeticException :/ by zero


Java exception handling Nestd tryn

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org