title: In Java, is the "finally" block guaranteed to be called (in the main method)?
body: <p>I'm a Java rookie and I was wondering, if I have the following typical Java code</p>
  
  <pre><code>public class MyApp {
    public static void main(String[] args) {
      try {
        // do stuff
      } catch {
        // handle errors
      } finally {
        // clean up connections etc.
      }
    }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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</p>
  
  <pre><code>try:
    # do stuff
  except AnExceptionIKnewMightHappen:
    # react in an appropriate way
  except:
    # log that weird error I had not known could happen
  </code></pre>
  
  <p>and I have never had any app die without passing through my code.</p>
  
  <p>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).</p>
  
  <p><strong>Edit:</strong> Just for clarity (it wasn't really misunderstood by anyone), let me add that I was looking for things <em>inside my code</em> 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.</p>
  
  <p>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.</p>