Question

I'm a Java rookie and I was wondering, if I have the following typical Java code

public class MyApp {
  public static void main(String[] args) {
    try {
      // do stuff
    } catch {
      // handle errors
    } finally {
      // clean up connections etc.
    }
  }
}

does the JVM guarantee that the finally block will always be run? To understand where I'm coming from, I'm used to C/C++ programs that might just crash if you dereference a NULL pointer and you can't have any code to be run after that.

But as I understand Java and the whole GC / managed memory business in general, there's no such thing as a null pointer dereferencing, everything is a catchable expection, so there's not really a way for my program to crash that could make it skip the finally, or is there? For example, in Python, I usually do

try:
  # do stuff
except AnExceptionIKnewMightHappen:
  # react in an appropriate way
except:
  # log that weird error I had not known could happen

and I have never had any app die without passing through my code.

Of course, if the OS for some reason kills the process (or if something kills the whole system, like pulling the plug) there's not much Java can do. Also, from PHP I know non-catchable errors that you can't protect against, even though the interpreter was still there after it happened (at least it is able to output a proper message).

Edit: Just for clarity (it wasn't really misunderstood by anyone), let me add that I was looking for things inside my code that could lead to the finally being bypassed. So pointing to System.exit was a helpful reminder, even though I can't see why I would want to do something like that.

The JVM exiting is a rather obvious way and I'd count that as an external cause. The note pointing out that you also have to remember the possibilty of threads exiting while the JVM and the app keep running was very helpful, because even though it also seems obvious to me now, I hadn't thought of it.

Was it helpful?

Solution

Basically yes, except for the note listed here (emphasis mine):

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.

OTHER TIPS

It is not guaranteed:

public class Main {
    public static void main(String args[]) {
        try {
            System.out.println("try");
            System.exit(0);
        } catch (Exception e) {
            System.out.println("exception");
        } finally {
            System.out.println("finally");
        }
    }
}

Run that.

In a word, yes.

Code in the finally block in Java always executes unless:

  • The JVM exits during the try or catch block
  • The thread running the code is interrupted or killed during the try or catch block

(from: http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html)

So, unless you explicitly call System.exit(int), or kill the process or thread externally, you can rely on it.

Absolutely, that finally block will run, every time. Except in the case of a JVM crash or the exit() function being called. I have had code where the Java application made calls out to JNI native code which segfaulted. The resulting crash killed the JVM, and prevented the finally from running.

Chris Cameron is correct. But normally a finally-block gets executed. Null pointer dereferece does exist in Java:

try {
    List<Object> x = null;
    x.get(1); //throws the unchecked NullPointerException
} finally {
    //will be executed
}

The finally-Block gets executed.

Yes, the JVM always executes it. Gaurranteed.

Of course ... if the JVM itself dies (eg: System.exit()), then it's not in a position to gaurrantee anything. But the JVM dying is not a within-java issue.

Erm, yep :) Whether your code enters a catch or not, the finally will run. It's a good place to put code that cleans up after the try.

Obviously it won't run if you break the jvm :)

Yes, the finally block will always be run, unless there is a crash of the JVM (very rare, but that can happen).

the only exceptions finally block is not executed are, either JVM crashes, or system.exit().

It seems pretty obvious that nothing more will run after JVM quit, or will run code in that killed thread. Obvious. So, when the JVM is running, every code that will run, will run, and after a JVM quit or inside a dead thread , nothing will run, even any kind of code. So, there is no way to prevent, but if there is a need to the finally clause, put it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top