Member-only story

Is the Code in the Finally Block Always Executed?

Gain Java Knowledge
2 min readNov 13, 2024

--

In Java, the finally block is generally guaranteed to execute after a try or catch block, regardless of whether an exception is thrown.

public class TestFinally {
public static void main(String[] args) {
try {
System.out.println("Inside try block");
} catch(Exception ex){
ex.printStackTrace();
}finally {
System.out.println("Inside finally block");
}
}
}

Output :

Inside try block 
Inside finally block

But, there are a few rare cases when the finally block may not execute:

  1. System.exit() Call: If System.exit() is called in the try or catch block, it will terminate the JVM immediately, preventing the finally block from executing.
try {
System.out.println("In try block");
System.exit(0); // JVM exits, skipping finally
} finally {
System.out.println("In finally block"); // Won't execute
}

Output :

In try block

2. Runtime.getRuntime().halt()

When encountering the code Runtime.getRuntime().halt() in the try block, it forcibly terminates the running JVM. Unlike the System.exit() method, this method does not trigger the JVM…

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet