Search code examples
javasignalsfinally

If I type Ctrl-C on the command line, will the finally block in Java still execute?


I'm running my Java application in cmd.exe in Windows. If I stop the process forcefully by pressing Ctrl-C, and the code at that moment was running in the try block, will the finally block still be executed?

In my tests it seems that, yes, it is executed.


Solution

  • While your finally code may have executed on your Windows machine (I couldn't reproduce it with Linux), according to this documentation on finally:

    Note: If the JVM exits while the try or catch code is being executed, 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.

    So I wouldn't use a finally block to make sure a piece of code executes, even if the user tries to prematurely exit. If you need that, you can use, like Adrian Petrescu mentioned, Shutdown Hooks