This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt with Dan's Mock exam - Flow Control & Exception Handling Q7

 
Priya Venkatesan
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody explain why the result comes out this way.
class Level1Exception extends Exception {}
class Level2Exception extends Level1Exception {}
class Level3Exception extends Level2Exception {}
class Brown {
public static void main(String args[]) {
int a, b, c, d, f;
a = b = c = d = f = 0;
int x = 1;
try {
switch (x) {
case 1: throw new Level1Exception();
case 2: throw new Level2Exception();
case 3: throw new Level3Exception();
}
a++;
}
catch (Level3Exception e) { b++;}
catch (Level2Exception e) { c++;}
catch (Level1Exception e) { d++;} // Doubt
finally {f++;}
System.out.print(a+","+b+","+c+","+d+","+f);
}
}
Answer is 0,0,0,1,1
My question is why is that only the catch(Level1Exception e) is handling inspite of the case 2 and 3 statements throwing Level2Exception and Level3Exception respectively. Is it because Level1Exception is the super class?
 
sun par
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When Level1Exception is thrown, it does not execute the following statements, the compiler searches for a handler to handle the exception. Since it is Level1Exception that is thrown handler for Level1Exception is invoked.
 
Priya Venkatesan
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You. I got it.
 
Sarma Lolla
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When ever an exception is thrown the following code is completely skipped and next executed statement is catch block. If catch block is not present for the current try block compiler searches for finally block. If finally is found then it is executed and compiler searches for catch blocks if any are present in the nested try block....
try{
// throw exception
try{
}
finally{
// don't return here. We still have some work..
}
catch{
// this is executed for the above exception
}
}
[ March 10, 2003: Message edited by: Sarma Lolla ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic