Member-only story
Is the Code in the Finally Block Always Executed?
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:
- System.exit() Call: If
System.exit()
is called in thetry
orcatch
block, it will terminate the JVM immediately, preventing thefinally
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…