Unreachable statement compile error in Java [duplicate]

痴心易碎 提交于 2019-11-27 21:36:19

Does it mean that compiler checks whether it is able to compile for all branches/lines of code ?

It means the compiler checks that every statement is reachable.

From section 14.21 of the JLS:

It is a compile-time error if a statement cannot be executed because it is unreachable.

This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements.

The section then documents how reachability is defined.

In particular, the relevant points in your case are:

Every other statement S in a non-empty block that is not a switch block is reachable iff the statement preceding S can complete normally.

A break, continue, return, or throw statement cannot complete normally.

So your "line 1" statement is preceded by a statement (break;) which cannot complete normally, and therefore it's unreachable.

The compiler is also able to make that conclusion, and assumes you are making a mistake. And yes, the Java compiler does a pretty good amount of "Data-Flow Analysis". The most common related message is the one about variables not initialized. The second most frequent is, I believe, precisely this one, about code not reachable.

Does it mean that compiler checks whether it is able to compile for all branches/lines of code ?

Yes compiler compiles the whole body of code and make byte code according to your code, it smarter enough to detects unreachable code also dead code. Immediate break in the for-loop makes unreachable other statements.

for(;;){
   break;
   ... // unreachable statement
}


int i=1;
if(i==1)
  ...
else
  ... // dead code
Aniket Thakur

Unreachable code is meaningless and redundant. If you have some unreachable code in your program it is a mistake and needs to be fixed. Hence compiler throws an error.

You can refer to similar questions below

Unreachable code: error or warning? and Why does Java have an "unreachable statement" compiler error?

The compiler is able to determine that these two statement will never, ever be executed, and helps you write correct code by refusing to compile it, because this has 99.9% chance of being an error rather than a conscious choice to add statements that will never be executed.

The compiler will check if there is more code after certain keywords. Another keyword which will cause a similar message is if you replace break by return.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!