Why is try-with-resources catch block selectively optional?

前端 未结 5 702
清酒与你
清酒与你 2021-02-02 08:43

I read that the catch block in try-with-resources is optional. I\'ve tried creating a Connection object in a try-with-resources block, with no subsequ

5条回答
  •  情歌与酒
    2021-02-02 09:26

    It is optional if close() is not able to throw a checked exception. However, if close() can, then a checked exception would need to handled in a normal fashion, either with a catch block, or by throwing from the method that try-with-resources block is in.

    More details are in JLS 14.2.3

    14.20.3.2. Extended try-with-resources

    A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.

    The meaning of an extended try-with-resources statement:

    try ResourceSpecification
        Block
    [Catches]
    [Finally]
    

    is given by the following translation to a basic try-with-resources statement nested inside a try-catch or try-finally or try-catch-finally statement:

    try {
        try ResourceSpecification
           Block
    }
    [Catches]
    [Finally]
    

    The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

    Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

    Thoughts on whether or not this is related to the use of a JNDI DataSource?

    Yes, it is.

    In the example try-with-resourses block you've provided, it is necessary to catch the exception and handle, or throw from the method the block is in, because SQLException is a checked exception.

提交回复
热议问题