Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 384
Hesey Avatar asked Feb 06 '11 05:02

Hesey


People also ask

Does finally block always execute in Java?

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.

What does Ctrl C do in Java?

ctrl c is used to kill a process. It terminates your program.

When finally block is not executed in Java?

Note: The finally block may not execute if the JVM exits while the try or catch code is being executed.

When finally block gets executed in Java?

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.


1 Answers

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.

like image 147
Adrian Petrescu Avatar answered Sep 28 '22 06:09

Adrian Petrescu