java - "Unreachable Code"条件在Java中什么时候出现?

标签 java unreachable-code

当无限循环之后写了一些语句,那条语句就变成了不可达代码。例如:

for(;;) 
{
}
Sytem.out.println("Test-1"); //unreachable code

但是我在这里遇到了一些困难。

请看下面的两个代码片段:

代码片段1:

for(final int z=4;z<6;)
{
}
System.out.println("Test-2"); //unreachable code

这里,最后一条语句一定是不可达的,因为循环是无限的,输出是预期的。

代码片段2:

final int z=4;
for(;;)
{
    if(z<2)
        break;
}
System.out.println("Test-3");  //not unreachable

从概念上讲,上面代码中的 for 循环也是无限的,因为 z 是最终的并且 if(z<2)仅在编译时确定。if 条件永远不会为真,循环也永远不会中断。 但是,上面代码中的 Last 语句并非不可访问。

问题:

  1. 为什么会这样?

  2. 谁能告诉我判断代码是否不可访问的确切规则。

最佳答案

http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21 中的关键词是:

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. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

因此编译器不评估 z<2在你的if()声明,并且不知道 它永远不会评估为 true .

就 Java 规范而言,这定义了无法访问的代码。编译器遵守规范很重要,因为更改规则可能会使用于编译的代码无法编译。

但是,编译器可以自由地给出警告而不是编译错误。

如果我在 Eclipse 中键入以下代码:

final int x = 0;
if(x == 1) {
    System.out.println("This never happens");
}

...我收到警告“死代码”。编译器知道无法访问代码 - 但它不能拒绝编译,因为根据 Java 规范,代码并不是正式的“无法访问”。

关于java - "Unreachable Code"条件在Java中什么时候出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24181028/

相关文章:

java - 如何将actionPerformed分配给特定的actionListener?

java - 无法访问的 return 语句仍然抛出错误

java - 如何在Java中设置SOAP连接超时?

C# Excel 函数 - 检测到无法访问的代码

python - 抑制 PyDev 中无法访问的错误?

java - 返回时无法访问代码 START_STICKY;

java - 运行此程序时出现无法访问的代码错误,但我不知道为什么

Java线程可以调用公共(public)数据收集器对象的方法吗?

java - 什么是有效的 UUID?

java - 使用 RetroFit for Android 解析嵌套的 JSON