Why does Java allow for labeled breaks on arbitrary statements?

前端 未结 9 1851
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 13:16

I just learned today that the following Java code is perfectly legal:

myBlock: {
    /* ... code ... */

    if (doneExecutingThisBlock())
        break myBlock;         


        
9条回答
  •  余生分开走
    2021-02-07 13:37

    Why make it so that you can only break out of certain enclosing statements using labeled breaks but not regular breaks

    Consider:

    while (true) {
        if (condition) {
            break;
        }
    }
    

    If the break did as you suggest, this code would perform unexpectedly. Breaks would become a lot more difficult to use.

    And why allow for this behavior at all?

    I don't use it, but it is a feature and allows for certain unique control-flow constructs. I'd ask you, why not allow it?

提交回复
热议问题