Try-with-resources scope of resource

前端 未结 4 1524
旧巷少年郎
旧巷少年郎 2021-01-07 23:43

In the try-with-resources construct of Java 7, I can declare a resource in the try statement, and it will be closed autom

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-08 00:25

    This syntax is called Extended try-with-resources

    As per JLS:

    try ResourceSpecification
        Block
    Catchesopt
    Finallyopt
    

    Will be translated to:

    try {
        try ResourceSpecification
            Block
    }
    Catchesopt
    Finallyopt
    

    So, in your example, your resource will be limited to inner try block, so not available for outer try/catch/finally.

    EDIT:

    my question does not have nested try blocks

    By explicitly adding catch/finally block in your code, you are introducing nested try blocks.

提交回复
热议问题