Is finally block really necessary for the clean up code (like closing streams)?

前端 未结 8 2202
情歌与酒
情歌与酒 2021-02-15 10:14

I am very confused as to why do I need to need to put the clean-up code like closing streams in a finally block.

I\'ve read that the code in finally<

8条回答
  •  迷失自我
    2021-02-15 11:03

    after the finally block runs rest of the method continues

    This is only true if there was no exception caught. If an exception happens inside the try block the catch block will be executed (if there is one for this exception), the finally block will be executed, and then control is given to the caller of the method if the catch block throws the exception further, without running any further code in this method.

    EDIT: clarify that catch would have to return of course, and not just eat the exception.

提交回复
热议问题