Search code examples
javaexceptionrethrow

how does rethrow exception terminate by outer catch?


enter code here
  `class Rethrow
   {
    public static void genException()
   {
        int n[]={4,8,16,32,64,128};
        int d[]={2,0,8,0,4};

        for(int i=0;i<n.length;i++)
        {                                     
            try{
                System.out.println("n/d is:"+n[i]/d[i]);

               }
            catch(ArithmeticException exc)
              {
                System.out.println("Cant Divide By Zero");
                throw exc;
              }
            catch(ArrayIndexOutOfBoundsException exc)
             {
                System.out.println("No match element found ");
                // rethrow the exception
             }
        }
    }
}

class RethrowDemo
{
    public static void main(String args[])
    {
        try 
        {
            Rethrow.genException();
        }
        catch(ArithmeticException exc)  // catch the rethrow Exception
        {
            // recatch exception
            System.out.println("Fatal Error "+"Program Termiated.");
        }
    }
}

this is output of program

Question 1::why does catch of "RethrowDemo" CLASS terminate an exception thrown by catch(Arithmetic Exception) of "Rethrow" class.

Question 2:: how does transfer of control working ??


Solution

  • In Java, when an event occurs that disrupts the normal flow of your application an Exception object is created and it is passed up the call stack to either be dealt with by the caller or passed further up to be dealt with/handled by something else higher up in the hierarchy.

    Due to the fact you can't divide by zero an ArithmeticException is thrown from the line System.out.println("n/d is:"+n[i]/d[i]); and since you're doing this within a try...catch block, your catch(ArithmeticException exc) says "If there is an ArithmeticException thrown from within the try then I'm here to deal with it".

    It is in this catch block you are printing out Cant Divide By Zero and then re-throwing the original exception. This then bubbles up to the calling method, in your case to the main method but since you are making the call from within a try...catch(ArithmeticException exc) that catch in main says "I will deal with that ArithmeticException that you have just re-thrown". It is at this point you then print Fatal Error Program Termiated and the application ends.

    There are plenty of tutorials that will explain fully how exceptions work in Java so it would be useful to take a look at a few.

    A Tutorial on Exceptions

    Another Tutorial on Exceptions