Java Finally Block – When it is not executed ?

The finally block in Java is used to define a section of code that will always be executed, regardless of whether an exception is thrown or caught. However, there are certain conditions under which the finally block may not execute. In this tutorial, we’ll explore these conditions and provide some code snippets to illustrate them. Hint: read it through as this is a common interview question!

JVM crash or System.exit()

One of the conditions when the finally block may not get executed is if the JVM crashes or the program is terminated using System.exit() method. The same applies if you are terminating the JVM from your Operating System (f.e. a “kill -9” command).

In these cases, the finally block will not have a chance to execute. Here’s a code snippet that demonstrates this:

public static void main(String[] args) {
    try {
        // Some code here
        System.exit(0);
    } finally {
        System.out.println("This will not be executed");
    }
}

Infinite loop or other non-terminating code

Another condition under which the finally block may not execute is when the program is caught in an infinite loop or other non-terminating code. In such cases, the finally block will not have a chance to execute because the program is stuck in an endless loop. Here’s a code snippet that demonstrates this:

public static void main(String[] args) {
    try {
        while (true) {
            // Some code here
        }
    } finally {
        System.out.println("This will not be executed");
    }
}

Thread killed

A third condition under which the finally block may not execute is when a Thread is killed using the stop() method. When this happens, the finally block will not be executed. Here’s a code snippet that demonstrates this:

public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(() -> {
        try {
            Thread.sleep(1000);
        } finally {
            System.out.println("This will not be executed");
        }
    });
    thread.start();
    thread.stop();
}

Invoking Runtime.getRuntime().halt(exitStatus)

When you call Runtime.getRuntime().halt(exitStatus), the JVM will immediately stop without running any further code, including any code in the finally block. This method is commonly used for emergency situations where you need to stop the JVM immediately, without waiting for any pending operations to complete. Here’s an example to demonstrate:

public static void main(String[] args) {
    try {
        // Some code here
        Runtime.getRuntime().halt(1);
    } finally {
        System.out.println("This will not be executed");
    }
}

Daemon thread and all non-daemon threads have exited

In Java, daemon threads are threads that are created with the setDaemon(true) method, which means they will not prevent the JVM from exiting. If a finally block is executed by a daemon thread, and all other non-daemon threads have already exited, then the finally block will not execute. Here’s an example to demonstrate:

public static void main(String[] args) throws InterruptedException {
    Thread daemonThread = new Thread(() -> {
        try {
            Thread.sleep(1000);
        } finally {
            System.out.println("This will not be executed");
        }
    });
    daemonThread.setDaemon(true);
    daemonThread.start();
    Thread.sleep(500);
}

System error

The last condition under which the finally block may not execute is when a system error occurs, such as a power outage or hardware failure. When this happens, the finally block will not have a chance to execute. Here’s a code snippet that demonstrates this:

public static void main(String[] args) {
    try {
        // outage here
    } finally {
        System.out.println("This will not be executed");
    }
}

Conclusion

In conclusion, the finally block in Java is designed to execute code that should always be executed, regardless of any exceptions or errors that may occur. However, there are certain conditions under which the finally block may not execute, such as a JVM crash or system error, an infinite loop, a Thread that is killed, or a call to System.exit(). It’s important to be aware of these conditions so that you can write code that behaves correctly in all situations.

Found the article helpful? if so please follow us on Socials