问题
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?
回答1:
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
.
回答2:
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.
回答3:
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.
回答4:
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.
回答5:
If you call System.exit()
your code won't execute finally
, because that call terminates your JVM.
来源:https://stackoverflow.com/questions/14905006/system-exit-results-unexecutable-finally-block