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

前端 未结 8 2536
小蘑菇
小蘑菇 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:12

    The finally block will always run if an uncaught exception is thrown, but the rest of the code in the method will be skipped.

    So if you put clean-up code after the finally block, it won't get called if there is an exception.

    0 讨论(0)
  • 2021-02-15 11:16

    My question is; if the rest of the method has to continue then why not I put the clean code after my try/catch block in a function.

    You can do so but you have to call this function again in finally block by passing object references( non-java resources) that needs to be closed. Because if this function is not finally block and if any exception occurs your entire method will be skipped without closing non-java reources.

    Also you can use java7 feature -> try-catch with resources. Non-java resources will be automatically closed. You do not need to use finally block.

    0 讨论(0)
提交回复
热议问题