aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt with Dan's Mock exam - Flow Control & Exception Handling Q7 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt with Dan Watch "Doubt with Dan New topic
Author

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

Priya Venkatesan
Ranch Hand

Joined: Nov 02, 2002
Posts: 61
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

Joined: Oct 03, 2002
Posts: 257
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.


Sunita<br />SCJP 1.4
Priya Venkatesan
Ranch Hand

Joined: Nov 02, 2002
Posts: 61
Thank You. I got it.
Sarma Lolla
Ranch Hand

Joined: Oct 21, 2002
Posts: 203
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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Doubt with Dan's Mock exam - Flow Control & Exception Handling Q7