views:

2702

answers:

12

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.

A: 

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 :)

Robert Grant
+25  A: 

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

Basically, yes, except for the note listed there:

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

Chris Cameron
Note that pulling the power cord is usually a good way to prevent "finally" from running, too...
Bill Michell
LOL - and if it's a laptop, the batteries in the laptop die at the same moment :D
Chris Cameron
Dropping the laptop out of the top story of a sky scraper also prevents both finally blocks *and* shutdown hooks!!
Software Monkey
A: 

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

Guillaume
+8  A: 

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.

cletus
Not quite sure how that's relevant to "so there's not really a way for my program to crash that could make it skip the finally, or is there?"Obviously if you quit the JVM, powercycle the box or shoot the monitor then finally won't run. Surprised at the up-votes, but then maybe I'm just jealous :)
Robert Grant
It's simple proof by counterexample. Obviously it's not guaranteed. That may or may not be important to you. And if it happens on a "clean" exit, I guarantee you it's no better on an actual crash.
cletus
I think that it's safe to say System.exit() is a special case
matt b
Special or not, it's a case and a valid one at that. There's a HUGE difference between "finally is guaranteed" and "finally is normally guaranteed".
cletus
To add my 2ct, I thought it was a helpful reminder that you actually can bypass it with ordinary code (i. e. without errors), even though I can't think of a reason right now why I should want to exit the program that way. I'm new to Java and it helped.
Hanno Fietz
+5  A: 

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.

Martin McNulty
+2  A: 

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.

Arcane
+2  A: 

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.

Johannes Weiß
That's interesting, I didn't know that. Although it's still quite different from a classic C segfault.
Hanno Fietz
A: 

This is an exact duplicate of this question.

starblue
Right. When I entered my question, I had the equivalent for .Net among the suggested "similar posts" but not that one. Weird. I guess, to avoid duplicates, you have to do an explicit search first and not rely on the automatic suggestions.
Hanno Fietz
+2  A: 

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.

paulmurray
A: 

ok, the finally block will always be executed, unless the JVM exits. How could I make then a pseudo "finally" method that is executed in case, for example, I press ctrl+c during the execution?

Giulio
A: 

Ok I found a solution to my problem. and I wrote an article about it on wikijava:

www.wikijava.org

Giulio