1

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?

ManuPK
  • 11,623
  • 10
  • 57
  • 76
  • 2
    possible duplicate of [Unreachable code compiler error](http://stackoverflow.com/questions/9276378/unreachable-code-compiler-error) – Tomasz Nurkiewicz Mar 01 '12 at 13:32
  • Possible duplicate of http://stackoverflow.com/questions/2141029/unreachable-code-error-vs-dead-code-warning-in-java-under-eclipse – Alexander Pavlov Mar 01 '12 at 13:34
  • It's quite intentional, and overall the right way to do it. What's absent is a decent conditional compilation scheme. – Hot Licks Mar 01 '12 at 13:37

2 Answers2

6

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.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

It is a limitation of how far you go to check you have dead code or code which will never run.

The JVM can detect the code is dead and not compile it.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130