Java中无法访问的语句编译错误 [英] Unreachable statement compile error in Java

查看:149
本文介绍了Java中无法访问的语句编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class For1
{
  public static void main(String args[])
  {
    int a = 0;
    for(;;)
    {
      break;
      System.out.println(a); //Line 1
      ++a;//Line 2
    }
  }
}

我知道第1行/第2行永远不会执行。
但我仍然不明白为什么会抛出编译时错误。
我得到无法访问的语句编译错误。

I know that Line 1/Line 2 will never be executed. But still I don't understand why a compile time error is thrown. I am getting "unreachable statement" compile error.

这是否意味着编译器检查它是否能够为所有分支/代码行编译?

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

推荐答案


这是否意味着编译器会检查它是否能够为所有分支/代码行编译?

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.

来自 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.

然后该部分记录了如何定义可达性。

The section then documents how reachability is defined.

特别是,您的案例中的相关点是:

In particular, the relevant points in your case are:


非空块中的每个其他语句S如果S之前的语句可以正常完成,那么不是交换块是可以访问的。

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 继续返回,或 throw 语句无法正常完成。

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

所以你的第1行语句前面有一个语句( break; 无法正常完成,因此无法访问。

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

这篇关于Java中无法访问的语句编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆