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

exceptions

 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone explain this code step by step how the control passes
class Level1Exception extends Exception {}
class Level2Exception extends Level1Exception {}
class Level3Exception extends Level2Exception {}
class Purple {
public static void main(String args[]) {
int a,b,c,d,f,g,x;
a = b = c = d = f = g = 0;
x = 3;
try {
try {
switch (x) {
case 1: throw new Level1Exception();
case 2: throw new Level2Exception();
case 3: throw new Level3Exception();
} a++; }
catch (Level2Exception e) {b++;}
finally {c++;}
}
catch (Level1Exception e) { d++;}
catch (Exception e) {f++;}
finally {g++;}
System.out.print(a+","+b+","+c+","+d+","+f+","+g);
}}
O/P is 0,1,1,0,0,1

and in the same way i suppose the next code below
class Level1Exception extends Exception {}
class Level2Exception extends Level1Exception {}
class Level3Exception extends Level2Exception {}
class Purple {
public static void main(String args[]) {
int a,b,c,d,f,g,x;
a = b = c = d = f = g = 0;
x = 2;
try {
try {
switch (x) {
case 1: throw new Level1Exception();
case 2: throw new Level2Exception();
case 3: throw new Level3Exception();
} a++; }
catch (Level2Exception e) {b++;}
finally {c++;}
}
catch (Level1Exception e) { d++;}
catch (Exception e) {f++;}
finally {g++;}
System.out.print(a+","+b+","+c+","+d+","+f+","+g);
}}

O/P same 0,1,1,0,0,1
 
Seb Mathe
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ex1
1- x=3 so entering "case 3" -> throw new Level3Exception();
2- catch(Level2Exception ex) in the inner try block because "Level3Exception is a Level2Exception"
3- b++ -> b=1
4- doing finally of the inner try block : c++ -> c=1
5- doing finally of the outer try block: g++ > g=1
6- output

Ex2
You're right, it's the same flow.
 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey thanks, gotta know aftr u explained,didnt go thru the code properly
anyway thanks
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hope you got it..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic