Try-with-resources scope of resource

前端 未结 4 1527
旧巷少年郎
旧巷少年郎 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:24

    The correct scope limitation is within the declaration part (...) and the actual try block.

    The JLS states

    The scope of a variable declared in the ResourceSpecification of a try-with-resources statement (§14.20.3) is from the declaration rightward over the remainder of the ResourceSpecification and the entire try block associated with the try-with-resources statement.

    So from the point it is declared in the ResourceSpecification (...) of the try onwards until the final closing } bracket of the try Block.

    TryWithResourcesStatement:
        try ResourceSpecification Block Catchesopt Finallyopt
    
    ResourceSpecification:
        ( Resources ;opt )
    
    Resources:
        Resource
        Resource ; Resources
    
    Resource:
        VariableModifiersopt Type VariableDeclaratorId = Expression
    

提交回复
热议问题