StackOverflow 上有大量与 Java 中的 of use break
语句相关的答案。 ,但不幸的是,我无法找到对我的 Java 初学者类型问题的明确解释。
// Main.java
public class Main {
public static void main(String[] args) {
foo: {
break foo; // compiles and executes OK
}
bar: {
// Java compiler produces an error at this point
break;
}
// perhaps Java compiler complains on unused label, but...
baz: {
System.out.println("Hello World"); // compiles and executes OK
}
}
}
javac Main.java
Main.java:10: error: break outside switch or loop
break;
^
1 error
我错过了什么?
最佳答案
break
语句有两种形式,一种不带标签,一种带标签。
您的第一个案例可以编译,因为有一个同名的相应标签标记了要中断的语句。
但在第二种情况下,没有标签,需要一种特定类型的语句来打破。根据JLS, Section 14.15 :
A
break
statement with no label attempts to transfer control to the innermost enclosingswitch
,while
,do
, orfor
statement; this enclosing statement, which is called the break target, then immediately completes normally.A
break
statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this enclosing statement, which is called the break target, then immediately completes normally. In this case, the break target need not be aswitch
,while
,do
, orfor
statement.It is a compile-time error if a
break
statement has no break target.
没有封闭的switch
、while
、do
或for
; block 不满足此要求,因此没有中断目标。由于没有中断目标,因此出现编译错误。
带有显式标签的break语句只需要一个带标签的语句,其中可以包含带大括号的 block 。
关于java - 使用未标记的break语句会导致编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74790758/