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

前端 未结 5 708
清酒与你
清酒与你 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:25

    You could check the JLS but there is actually a relatively easy reasoning why this is the only correct way the language should behave.

    The main rule of checked exceptions is that any checked exception declared by a method must be handled, either by catching it or letting the calling method throw it.

    The try-with-resources always (implicitly) calls the close method.

    So if the specific close method of the AutoClosable you use (determined by the type declared in try) declares to throw a checked exception such as a SQLException you do need to handle this checked exception somewhere, otherwise it would be possible to violate the rule!

    If the close method does not declare that it throws a checked exception, the rule is not violated and you do not need to handle a checked exception for implicitly calling the close method. It is actually a compilation failure if you do try to catch a checked exception that is never declared to be thrown.

提交回复
热议问题