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.
A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.
ctrl c is used to kill a process. It terminates your program.
Note: The finally block may not execute if the JVM exits while the try or catch code is being executed.
inside try block 17 finally : i execute always. In this case, the program throws an exception but handled by the catch block, and finally block executes after the catch block.
The correct way to ensure that some code is run in response to an operating system signal (which is what Ctrl-C does, it sends a SIGINT) is to register a "shutdownHook". Here's a StackOverflow question about handling it, and here's an article with way more detail about the JVM's signal handling than you probably will ever want to know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With