Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP 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