When the finally block fails, when the try or catch block breaks

when the finally block will not be executed, when the block is interrupted or blocked? the document states that "if the thread executing the try or catch code is interrupted or killed, the finally block may not be executed, even if the application as a whole continues." can anyone give an example about this situation?

+4
source share
4 answers

Good answers can be found here .

Besides System.exit() , the finally block will not work if the JVM fails for some reason (for example, an infinite loop in the try block).

As for the thread itself, only if it is stopped using the stop() method (or suspend() without resume() ), the finally block will not be executed. A call to interrupt() will still execute the finally block.

It's also worth noting that since any return in the finally block will override any returns or exceptions in the try / catch blocks, the program’s behavior can quickly become unstable and difficult to debug if this happens to you. Actually, it’s not worth taking precautions (as it happens only in extremely rare cases), but you should be aware that you can recognize it when this happens.

+8
source

The only legal way to make finally not execute is to call System.exit or Runtime.halt in try or catch

+7
source

Suddenly terminating the application before it, for example

 System.exit(); 

Even after returning before the finally block (for example, in the try block) it will be executed after finally .

+1
source

This applies to things that are (mostly) outside the shell of regular Java execution.

  • If your thread (successfully) calls System.exit() in a try block or catch , this call will not "terminate" in the sense used in JLS. The same thing happens if another thread calls System.exit() . In this case, the JVM triggers disconnect hooks.

  • If the JVM (hard) crashes, all Java activity stops instantly.

  • If the OS (hard) kills the JVM process, all Java activity stops acting instantly.

  • If the power to the CPU chip is turned off ...

+1
source

Source: https://habr.com/ru/post/1489267/


All Articles