In Java Exception Handling, finally block will always be executed irrespective of any exception in the try-and catch block. However, there are two scenarios in which the finally block may not be executed.
#1 – System.exit(0)
When System.exit(0) is used, the JVM will exit and the finally block will not be executed
public static void systemExitFinally() {
System.out.println("#1 - System.exit(0)");
try {
System.out.println("Hello from try");
throw new Exception();
} catch (Exception e) {
System.out.println("Hello from catch");
System.exit(0);
} finally {
System.out.println("Hello from finally");
}
}
#2 – Infinite Loop
When we use the infinite loop, the finally block will not be executed. To create an infinite loop, we’ll use while true(which will run until we stop the execution or JVM runs of out memory). An infinite loop prevents the block from exiting. The finally block will not get executed until the block exits.
public static void infiniteLoopFinally() {
System.out.println("#2 - Infinite Loop");
try {
System.out.println("Hello from try");
throw new Exception();
} catch (Exception e) {
System.out.println("Hello from catch");
while (true) {
}
} finally {
System.out.println("Hello from finally");
}
}
Example:
package TestAutomationCentral; public class FinallyBlockNotExecuted { public static void main(String[] args) { //TestAutomationCentral.com //Call below methods one by one systemExitFinally(); infiniteLoopFinally(); } public static void systemExitFinally() { System.out.println("#1 - System.exit(0)"); try { System.out.println("Hello from try"); throw new Exception(); } catch (Exception e) { System.out.println("Hello from catch"); System.exit(0); } finally { System.out.println("Hello from finally"); } } public static void infiniteLoopFinally() { System.out.println("#2 - Infinite Loop"); try { System.out.println("Hello from try"); throw new Exception(); } catch (Exception e) { System.out.println("Hello from catch"); while (true) { } } finally { System.out.println("Hello from finally"); } } }
These are commonly asked interview questions for Java. Hope, when the interviewer asked you, when the finally block will be not executed, you will be able to answer this Java Exception Handling interview confidently.