Search code examples
javaexceptiontry-catch-finally

Valid Commands That Keep A Finally-block From Executing in Java


So I've been assigned to teach a block on exception handling, and I've run into a question I don't have an answer for. What valid (e.g., don't result in either a compiler, or a run-time, error) commands in Java will keep a finally-block from executing?

A return statement won't do it, but a System.exit(0) statement will. My understanding is that a finally-block would execute no matter what. What (valid) statements will prevent a finally-block from doing so, and why?


Solution

  • Quoting Docs:

    If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    Regarding your example about System.exit(), quoting Docs again

    Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

    which means that finally will not be executed.

    Simple example:

    try {
        System.out.println("try");
        System.exit(0);
    } finally {
        System.out.println("finally");
    }
    

    The above example will print only try but not finally