• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

unreachable code

 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why there is unreachble code compilation error at line 2 only? Why not at line 1?
 
Saravanakumar Rajmohan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
when compiler encounters the method invocation
statement "throwit()" it checks to see if there are any handlers for the exception thrown by throwit(). if not, then the method which invoked
throwit() must declare that exception in its
throws clause, otherwise a compile time error occurs. However in this case there is an exception handler that handles the exception thrown by throwit().
But the key here is the compiler knows that throwit() method can throw an Exception but the excution of the method as such can throw that exception or it might complete normally.This can be known only at run time when the method executes.
But when it encounters "throw new Exception()" at line 2 it knows for sure that execution of this statement will throw an exception "defintely for sure" . so any statement after this statement will not be executed until it finds an appropriate catch clause and begins executing it.
i hope this helps
Saravanakumar R
 
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.
A throw statement cannot completely normally. Therefore, a statement following a throw statement is unreachable.
When you and I look at the method throwit, we think - well, that method will never complete normally. It is not one of the rules (JLS 14.20 Unreachable Statements) for the compiler to analyze the method.
[ July 15, 2003: Message edited by: Marlene Miller ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic