I am working on My application's under maintanace module
try {
if (isUndermaintanace) {
System.exit(1);
} else {
prepareResources();
}
} catch (Exception e) {
printStack(e);
} finally {
cleanResources();
}
When I am passing isundermaintanace
true
finally not executing.
What am I missing? Is there any other way to do that?
Finally
's don't execute if you kill the VM (or if the VM dies some other way). System.exit() is a rather crude method of killing the program, whereas finally is a high level OOP concept. System.exit() bails very quickly, doing as little cleanup as possible.
If you went into task manager and killed the process or issued a kill -9
on the process would you expect a finally to execute? It's vaguely (very vaguely) the same thing.
There's a few things worth noting. In particular, I lied a bit in the first part of the post. It's misleading to liken System.exit()
to truly instantly killing a program. In particular, shutdown hooks are ran, and if configured, finalizers can actually be ran. Note, however, that the docs fairly strongly suggest against using runFinalizersOnExit
.
System.exit
exits the program immediately, bypassing any other code execution (such as finally
blocks). If you want to exit the program after finally
blocks run, throw an exception instead.
If JVM exits while the try or catch code is being executed e.g. System.exit()
, then the finally block may not execute. Likewise, 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.
The only exceptional case where finally block wouldn't execute is if you call 'System.exit(1)' before the finally block
, which is the expected behavior as System.exit(1)
would terminate JVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With