javaexception

Is the Java compiler is designed to work like this or is it a limitation?


Say I have below lines any in a Java class,

System.out.println("start");
if(true)//The compiler will give compile time error if I uncomment this. 
    throw new RuntimeException();
System.out.println("end");

The unreachable code error message will appear if the if(true) is commented. Why Don't the compiler know that the line under if(true) will always be executed?

Is the Java compiler is designed to work like this or is it a limitation?


Solution

  • It's deliberate part of the design around code reachability. See section 14.21 of the JLS which has a section at the bottom about this.

    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.