• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan's question

 
jioy uilo
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi dan
Can u pls explain this code to me ? confused...
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 = 1;
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);
}
}
 
Jose Botella
Ranch Hand
Posts: 2120
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, jioy.
Finally clauses always execute regardless of the throwing or not of an exception in try's . In this case "finally{ c++; } is executed after "catch(Level2Exception e)" failed to catch the thrown Level1Exception. Then "catch(Level1Exception e)" catches the exception. Eventually "finally{g++};" gets executed.
 
jioy uilo
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try {
try {
switch (x) {
case 1: throw new Level1Exception();
case 2: throw new Level2Exception();
case 3: throw new Level3Exception();
}
a++;
}

how come above segment compiled ? i tot that, a try statement shld end with a catch or finally clause ?
how did a++ managed to fit in ?
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi jioy
well, it does end at appropriate place. the "}" u see if of "switch" not of TRY...
regards
maulin
 
Francis Siu
Ranch Hand
Posts: 867
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi jioy
Let me add something according to Jose
I trace the coding once,because ensure the coding without compiler error.

Hope this help
 
jioy uilo
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Siu
I was caught in Dan's trap !!
 
Francis Siu
Ranch Hand
Posts: 867
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi jioy
I was caught in Dan's trap !!

Actually,when you do some Dan's mock question,make sure to look the coding carefully that without compiler error.
So,we should know how to do the compiler job,or to be a real compiler
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic