5

This question already has an answer here:

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?


  • Probably the only thing you can do is change System.exit(1) to shut down your app some other way. - Louis Wasserman

5 답변


15

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.


  • +1 for the first sentence alone. What an elegant way to put it. - corsiKa
  • But what about is there any other way to do that ?? ? - user000001
  • @user000001 Just editing my answer to address that. Notice that needing to run a finalizer after a System.exit() is a rather severe sign of broken design though. - Corbin
  • @Corbin +1 I didn't know about finalizers. - user000001

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.


2

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.


1

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.


1

If you call System.exit() your code won't execute finally, because that call terminates your JVM.

Linked


Related

Latest