java - 使用未标记的break语句会导致编译失败

标签 java javac

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 enclosing switch, while, do, or for 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 a switch, while, do, or for statement.

It is a compile-time error if a break statement has no break target.

没有封闭的switchwhiledofor; block 不满足此要求,因此没有中断目标。由于没有中断目标,因此出现编译错误。

带有显式标签的break语句只需要一个带标签的语句,其中可以包含带大括号的 block 。

关于java - 使用未标记的break语句会导致编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74790758/

相关文章:

java - 将 3rd-party jar 部署到 clojars?

java - 我们什么时候应该使用@PreAuthorize 和@Secured

java - 网络/代理身份验证(WebClient.UseDefaultCredentials 替代方案)

maven - JDK和Maven冲突

Java注解处理: Accessing "Element"s of non-annotated classes possible?

java - Riak/Java - 使用 AND 条件和排序对二级索引进行 MapReduce 查询的最佳实践

java - 如何动态加载 AttachProvider (attach.dll)

java - Ant测试编译找不到主类

java - 使用模块时如何修补 package-info.java 文件?

java - 为多目录项目制作文件