| Author |
Not reachable code
|
Kapil Sakhuja
Ranch Hand
Joined: May 09, 2001
Posts: 34
|
|
In the code above, at line marked 'LINE 2' the compiler rightly says that the code is not reachable, but it doesn't report the same problem with line marked as 'LINE 1'. Why can't the compiler see that the function fun() has only one line of code and that code is just throwing an exception, which means that the line 'LINE 1' will never execute in this code.
|
 |
Astha Sharma
Ranch Hand
Joined: Oct 15, 2011
Posts: 128
|
|
Compiler is not intelligent enough to predict the exception inside function call. It can not get at compile time that fun() can throw an exception. Instead of function call if you write-
compiler will get the error in this case.
|
 |
Kapil Sakhuja
Ranch Hand
Joined: May 09, 2001
Posts: 34
|
|
Thanks Astha!
I tried to look at the JLS and this is what i could follow from the same: The compiler follows a process called as 'static analysis' and so it knows that 'only' in the case of break, continue, return or throw statement, the code cannot complete 'normally' and so any statement after one of these statements becomes not reachable. A function call is treated like other expressions, and so the compiler is not able to make out whether this call will complete normally or not.
|
 |
Astha Sharma
Ranch Hand
Joined: Oct 15, 2011
Posts: 128
|
|
|
oh...its interesting. thanks
|
 |
Seetharaman Venkatasamy
Bartender
Joined: Jan 28, 2008
Posts: 4503
|
|
Kapil Sakhuja wrote: The compiler follows a process called as 'static analysis' and so it knows that 'only' in the case of break, continue, return or throw statement, the code cannot complete 'normally' and so any statement after one of these statements becomes not reachable.
Plus, also with below kind of statement,
|
Not everything that counts can be counted, and not everything that can be counted counts-Albert Einstein
|
 |
Astha Sharma
Ranch Hand
Joined: Oct 15, 2011
Posts: 128
|
|
Seetharaman Venkatasamy wrote:
Plus, also with below kind of statement,
then why the following code generates no error?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 2687
|
|
|
Again, static analysis won't pick that up. b = true is an expression, not a compile-time constant. It happens to be an expression that always evaluates to true, but the compiler doesn't bother trying to work that out.
|
 |
Astha Sharma
Ranch Hand
Joined: Oct 15, 2011
Posts: 128
|
|
|
ok....thankyou
|
 |
 |
|
|
subject: Not reachable code
|
|
|