« Broken abstractions => broken code | Main | CruiseControl != Continuous Integration »

How not to handle exceptions from static code block in Java

Saw a post at taragana.com on "How To Handle Exceptions From Static Code Block in Java". It came down to advocating logging it and rethrowing a runtime exception which would "normally ends the program execution". Sorry, but I couldn't let this piece of extremely bad advice slide...

You should never throw any exception out of a static code block (aka static initializer). Not even a runtime exception.

Why? Static initializers are called when the class definition is loaded (e.g. by invoking Class.forName("foo.bar.Xyz")). Any exception thrown by the static initializer will be passed through to the invoker, which in many cases will log it and move on - not abort the JVM.

However - the class is still loaded. Future attempts to refer to it result in a very-hard-to-diagnose ClassDefNotFoundException - these can easily swamp your logs so that the original exception can not be located. By throwing the exception out, you've actually made it a lot harder to pin down the cause.

It's much better to not throw the exception then, but check to see if the class initialized properly when needed (e.g., inside the constructor, or inside static methods) and throw a meaningful exception (runtime or otherwise) at that point. Even better still, if you can swing it, would be to defer the initialization to that point. This helps avoid side effects caused by the class definition being used in a different way (e.g. being examined via reflection inside of a debugger).

Comments (2)

Henry:

Wrong, both of you.

It's perfectly fine to throw a RuntimeException in a static initializer, because the JVM will catch it and rethrow a java.lang.ExceptionInInitializerError, which is an Error and hence should not be caught.

Henry, you are wrong... not about the ExceptionInInitialzerError, which is merely the way the exception gets passed back, but because of the effect the exception has on the class definition. The NoClassDefFoundError which occurs on subsequent access to the class will drown that original exception.

And you can catch Errors. If you weren't allowed to catch them, they wouldn't descend from Throwable. There are many situations where you do want to deal with Errors - I'm sure if you stop to think of them, you will.

Post a comment


About

This page contains a single entry from the blog posted on July 7, 2006 1:57 PM.

The previous post in this blog was Broken abstractions => broken code.

The next post in this blog is CruiseControl != Continuous Integration.

Many more can be found on the main index page or by looking through the archives.

Creative Commons License
This weblog is licensed under a Creative Commons License.
Powered by
Movable Type 3.35