Why do we use finally blocks?

前端 未结 11 2275
甜味超标
甜味超标 2020-11-27 11:43

As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?

Code A:

try { /*          


        
11条回答
  •  借酒劲吻你
    2020-11-27 12:15

    Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finally block it will execute whether an exception is thrown or not...

    Your application may be a collection of threads, Exception terminates the thread but not the whole application, in this case finally is more useful.

    In some cases finally won't execute such as JVM Fail, Thread terminate, etc.

提交回复
热议问题