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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>