pagetop
Javablog
by Java coders, for Java coders RSS

Don’t throw exceptions from a static initializer

July 2nd, 2007 by James

This includes static members that are initialized as part of their declaration.

Why? Because it cancels classloading (for the containing class) and future references to that class result in a NoClassDefFoundError.

A far better approach is to wrap this in an explicit initialization method and call that. At least this way there’s an explicit contract and your caller can anticipate this failure mode, and try to deal with it. It also makes it possible to reinitialize your code using different configuration. Even better (but somewhat orthogonal) is to try to wrap it up in an Object (as opposed to a class) because this gives you the ability to maintain multiple “configuration sets” concurrently, and opens the door to sub-classing and general design goodness.

This isn’t a particularly long post, but it’s a pet peeve that has caused me many a lost (frustrating) hour.


This entry was posted by by James on Monday, July 2nd, 2007 at 7:36 pm, and is filed under Construction, Exceptions, Java, static. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



2 comments on “Don’t throw exceptions from a static initializer”

Perhaps the class depends on some condition so strongly that it makes no sense to let classloading complete normally.

I just tested this out (Java 6), and it seems that the resulting stack trace is quite readable (I wondered whether your lost hours were down to the exception being swallowed).

I’ve been burnt with this issue. Yes, the exception was lost and subsequent class references giving NCDFE Errors were really painfull to understand.

Only after remote debugging, was I able to figure out what happened.

Then again, exceptions should be easily filterable so that you can narrow down to a particular Java class if you are in a DEBUG mode. Since we had a huge amount of stdout and exception trace in our log file, I could NOT easily find out what was happening.

Leave a comment

Markdown is supported.

To include code snippets in your comment, use

<pre><code># lang java
... code here ...
</code></pre>

or use 4 spaces at the start of the line instead of using code and pre tags.

Comment feed: RSS