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

前端 未结 8 2529
小蘑菇
小蘑菇 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 11:09

    if the rest of the method has to continue then why do I not put the clean-up code after my try/catch block in a function.

    Because the clean-up of your code is related to your try to do an action that attempts to open resources etc and logically it should be as part of the final clause as it is the last action related to your try.
    It would not make sense for example to close a file or connection 100 lines later due to some processing you have to do before returning.
    You got the results. No exception, release the resources. Best to do it in finally so that your code is cleaner as it is always executed

提交回复
热议问题