Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.exit() results unexecutable finally block [duplicate]

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?

like image 612
Suresh Atta Avatar asked Feb 15 '13 23:02

Suresh Atta


4 Answers

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.

like image 163
Corbin Avatar answered Sep 22 '22 22:09

Corbin


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.

like image 35
jacobm Avatar answered Sep 23 '22 22:09

jacobm


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.

like image 42
nsgulliver Avatar answered Sep 24 '22 22:09

nsgulliver


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.

like image 29
PermGenError Avatar answered Sep 23 '22 22:09

PermGenError