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

前端 未结 8 2533
小蘑菇
小蘑菇 2021-02-15 10:09

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 10:57

    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.

提交回复
热议问题