The finally block is designed to execute regardless of whether an exception occurs or not. However, there are a few exceptional situations where the JVM may terminate before the finally block gets a chance to run.
Key Points: • Under normal circumstances, the finally block always executes. • If System.exit() is called inside the try or catch block, the JVM terminates immediately and the finally block is skipped. • The finally block may not execute if the JVM crashes due to a fatal system error. • Sudden power failure, operating system shutdown, or process termination can also prevent execution of the finally block. • These situations are rare and occur outside the normal exception-handling flow.
Example: If System.exit(0) is executed inside a try block, the JVM shuts down immediately and control never reaches the finally block.
Code Example:
public class Demo {
public static void main(String[] args) {
try {
System.out.println("Inside try");
System.exit(0);
} finally {
System.out.println("Inside finally");
}
}
}Output:
Inside try
Interview Tip: A concise interview answer is:
"The finally block executes in almost all cases. However, it will not execute if the JVM terminates before reaching it, such as when System.exit() is called, the JVM crashes, or the process is forcibly terminated."