Reputation: 4485
When i use this below code, compilation error happens.
try {
throw new Exception("Exceptionist");
System.out.println("another line"); //compilation error
}catch (Exception e) {
System.out.println("Exception:" + e.getMessage());
}
The reason for compilation error is that we cannot write code after throwing an exception. But when i try something like this
try {
if (true)
throw new Exception("Exceptionist");
System.out.println("another line"); // no compilation
} catch (Exception e) {
System.out.println("Exception:" + e.getMessage());
}
Even though the Eclipse IDE predicts the syso as dead code, why not java points it out. Even when it is getting compiled into bytecode the syso will never be executed. So why it is not taken as a compilation error. (i know its not a compilation error :| . May be, some other way of denoting it.) is it given for the programmer's choice ?
Upvotes: 1
Views: 56
Reputation: 691715
The explanation is in the Java Language Specification:
It is a compile-time error if a statement cannot be executed because it is unreachable.
[...]
if (false) { x=3; }
does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.
The rationale for this differing treatment is to allow programmers to define "flag variables" such as:
static final boolean DEBUG = false;
and then write code such as:
if (DEBUG) { x=3; }
The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.
So, even if the compiler can indeed remove the if (true)
from the bytecode because true is a constant expression, it still considers the code after the if
to be reachable, because it assumes this if
block is there to conditionally execute some code for debugging reason. You must be able to change the constant expression to from false
to true
and vice-versa and not modify anything else in the code to let it compile.
Upvotes: 3