System.exit () prints the final final block

I am working on My application under maintanace module

 try { if (isUndermaintanace) { System.exit(1); } else { prepareResources(); } } catch (Exception e) { printStack(e); } finally { cleanResources(); } 

When I go through isundermaintanace true without finally executing.

What am I missing? Is there any other way to do this?

+5
java try-catch-finally
Feb 15 '13 at
source share
5 answers

Finally they do not execute if you kill the VM (or if the VM dies in another way). System.exit () is a pretty crude method of killing a program, while finally it is a high-level OOP concept. System.exit () takes really fast, doing as little cleanup as possible.

If you went into the task manager and killed the process or released kill -9 in the process, did you expect it to finally execute? It is vaguely (very vaguely) the same.




There are a few things worth noting. In particular, I lied a bit in the first part of the post. This is misleading to liken System.exit() to really kill the program instantly. In particular, stop hooks are triggered and, if configured , finalizers can be triggered. Note, however, that the docs quite strongly indicate the use of runFinalizersOnExit .

+15
Feb 15
source share

System.exit will exit the program immediately, bypassing any other code execution (for example, finally blocks). If you want to exit the program after finally executing the blocks, throw an exception instead.

+2
Feb 15
source share

If the JVM shuts down while try or catch code is executed, for example. System.exit() , then the finally block may not execute. Similarly, if a thread executing try or catch code is interrupted or killed, the finally block may not be executed, even if the application as a whole continues.

+2
Feb 15 '13 at 23:24
source share

The only exceptional case where, finally, the block will not execute if you call "System.exit (1)" before the finally block , which is the expected behavior, since System.exit(1) terminated by the JVM.

+1
Feb 15
source share

If you call System.exit() , your code will not execute finally because this call terminates your JVM.

+1
Feb 15 '13 at 23:25
source share



All Articles