When finally block is not executed OR finally block always get executed in Java

The “finally” will be called after the execution of the try or catch code blocks. Some programmers think  finally block always executes, no matter what. But it’s not true.

Note: finally will be called after the execution of the try or catch code blocks.

Must Read- What is try-catch Java Block?

Some condition (cases) where “finally” won’t be called are:

  1. System.exit() invoked in block
  2. Runtime.getRuntime().halt(exitStatus)
  3. If the JVM crashes first
  4. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block
  5. If the OS forcibly terminates the JVM process; e.g., kill -9 <pid> on UNIX.
  6. If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called

Normal try-catch block code

In the example, the “finally” block always gets executed if the exception has occurred or not.

Output:

3
finally block is always executed

Let’s do try when finally block is not executed in java

1. System.exit(int)

The “finally block” will not execute due to the System.exit(1) condition in the try block. System.exit(0) doesn’t return, and the “finally block” is not executed.

Output: 3

2. Runtime.getRuntime().halt(exitStatus)

Output: Hello try

So the conclusion is that finally block will no always get executed in Java.

It could be your interview question, do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java finally block is not executed codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.