java - 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 zero"); throw exc; } catch(arrayindexoutofboundsexception exc) { system.out.println("no match element found "); // rethrow exception } } } } class rethrowdemo { public static void main(string args[]) { try { rethrow.genexception(); } catch(arithmeticexception exc) // catch rethrow exception { // recatch exception system.out.println("fatal error "+"program termiated."); } } }
question 1::why catch of "rethrowdemo" class terminate exception thrown catch(arithmetic exception) of "rethrow" class.
question 2:: how transfer of control working ??
in java, when event occurs disrupts normal flow of application exception
object created , passed call stack either dealt caller or passed further dealt with/handled else higher in hierarchy.
due fact can't divide 0 arithmeticexception
thrown line system.out.println("n/d is:"+n[i]/d[i]);
, since you're doing within try...catch
block, catch(arithmeticexception exc)
says "if there arithmeticexception
thrown within try
i'm here deal it".
it in catch
block printing out cant divide zero
, re-throwing original exception. bubbles calling method, in case main
method since making call within try...catch(arithmeticexception exc)
catch
in main
says "i deal arithmeticexception
have re-thrown". @ point print fatal error program termiated
, application ends.
there plenty of tutorials explain how exceptions work in java useful take @ few.
Comments
Post a Comment