Friday, May 29, 2009

Java: Try...Catch...Finally Flow

Note to self:
JAVA WILL ALWAYS EXECUTE THE FINALLY BLOCK*.

Hence, this code will work:

public static void main(String[] args)
throws Throwable {
try {
if (true) throw new RuntimeException("WOWZA!");
} catch (Exception e) {
throw e;
} finally {
System.out.println("REACHED!");
}
}

Yes, Java's output stream will read "REACHED," followed by the exception trace.

Even this code will work, and the finally block will be reached:

public String getString() {
try {
if (true) throw new RuntimeException("NOOOOOOOOOOO!");
return "STRING";
} catch (Exception e) {
return null;
} finally {
System.out.println("REACHED!");
}
}

Hope this helps someone out there.

* The only time Java will not execute a finally block is when it can't: eg when the JVM is shut down or the current thread is killed outright.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home