System.exit() results unexecutable finally block
java, system.exit, try-catch-finally
Solution
`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`.
Problem
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?