• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

An Exception question in Dan's mock exam

 
Yi Dong
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question is:
class ColorException extends Exception {}
class WhiteException extends ColorException {}
abstract class Color {
abstract void m1() throws ColorException;
}
class White extends Color {
void m1() throws WhiteException {throw new WhiteException();}
public static void main (String[] args) {
White white = new White();
int a,b,c,d;
a = b = c = 0;
try {
white.m1();
a++;
} catch (WhiteException e) {b++;}
finally {c++;}
System.out.print(a+","+b+","+c);
}
}
I thought a++ would never be reached, so there should be a compile-time error code not reachable, but it compiled fine. Can anybody explain to me why there is no such error, can a++ ever be reached ?
Thanks in advance
Yi
 
pradeepbill arumalla
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi there,
here is what i think,there is absolutely no problem if there is an unreachable statement in try block iff u have a proper Catch to catch the Exception thrown...please use JLS from the below link on unreachable statements...there is no special mention on try{} block unreachable statements...since the exception is thrown in between { & } it can be any where before or after a statement.
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#236365
thanks
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Java compiler must carry out a conservative flow analysis to make sure all statements are reachable. This analysis takes into account the structure of statements.

A method invocation can completely normally. Therefore, a statement following a method invocation statement is reachable.
When you and I look at the method m1, we think - well, that method will never complete normally. But it is not one of the rules for the compiler to analyze the method. (see JLS 14.20 Unreachable Statements)
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If you try above code, it will give compile time error you are looking for. Compiler checks upto certain level for unreachable code.
Thanks
Barkat
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic