Why use Finally in Try … Catch

前端 未结 14 1982
鱼传尺愫
鱼传尺愫 2020-12-05 06:38

I see that the Finally in Try .. Catch will always execute after any parts of the execution of the try catch block.

Is it any different to

14条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 06:43

    Finally contains code that needs to be evaluated at all conditions [whether or not an exception occurred].

    There is no way to exit a try block without executing its finally block. If the finally block exists, it always executes. (This statement is true for all intents and purposes. There is a way to exit a try block without executing the finally block. If the code executes a System.exit(0); from within a try block, the application terminates without the finally executing. On the other hand, if you unplug the machine during a try block, the finally will not execute either.)

    The main use is for disposing objects. It will be useful when you want to close user defined resources like file , opened resources(db stmts).

    Edit

    Also finally won't be executed after a stackoverflow exception.

提交回复
热议问题