问题描述
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 ?
推荐答案
这意味着编译器检查每个语句是否可达。
It means the compiler checks that every statement is reachable.
来自 JLS第14.21节:
本节专门用于对可达一词的精确解释。我们的想法是,必须有一些可能的执行路径,从构造函数,方法,实例初始化程序或包含语句的静态初始化程序开始到语句本身。分析考虑了陈述的结构。
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:
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中无法访问的语句编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!