Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does the finally block not execute while try or catch block is interrupted [duplicate]

Tags:

java

finally

when does the finally block not execute while try or catch block is interrupted? the doc says that "if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues." can someone give an example about this situation?

like image 270
andy Avatar asked Jul 02 '13 11:07

andy


3 Answers

Good answers can be found here.

Besides a System.exit(), the finally block will not run if the JVM crashes for some reason (e.g. infinite loop in your try block).

As far as the thread itself, only if it is stopped using the stop() method (or suspend() without resume()) will the finally block not be executed. A call to interrupt() will still result in the finally block being executed.

It's also worth noting that, since any return statement in the finally block will override any returns or exception throws in the try/catch blocks, program behavior can quickly become erratic and hard to debug if this happens to you. Not really anything worth taking precaution against (as it only happens in extremely rare cases), but worth being aware of so you can recognize it when it happens.

like image 145
Pat Lillis Avatar answered Oct 23 '22 05:10

Pat Lillis


The only legal way to make finally not execute is to call System.exit or Runtime.halt in try or catch

like image 7
Evgeniy Dorofeev Avatar answered Oct 23 '22 06:10

Evgeniy Dorofeev


Abruptly ending the application before it, e.g.

System.exit();

Even the return before finally block (e.g. in try block) will be executed after the finally.

like image 1
darijan Avatar answered Oct 23 '22 07:10

darijan