2

I was asked in an interview that when finally block does not execute. I replied that when JVM shuts down abruptly before the finally is called or when System.exit() is called. Then I was asked how can we avoid that scenario so that our program always remain executing. That is such a scenario should be handled. Can we handle such a scenario. If yes how? Thanks in advance.

Saket Kumar
  • 113
  • 1
  • 9

3 Answers3

2

Even finally fails but still shutdownhook will be executed.

Answer is -

Runtime#addShutdownHook

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or
    system shutdown.

Java docs

Code -

Runtime.addShutdownHook(new Thread {
  public void run() {
    System.out.println("Just before going down..");
  });
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

If you kill your system with a big enough gun, it will eventually stop being nice to you. You would have to have a redundant system in order for your code to keep going.

TubaBen
  • 196
  • 4
0

Java tutorial on oracle website says.

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

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.

http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Erdinç Taşkın
  • 1,548
  • 3
  • 17
  • 28