Saw a “post at taragana.com”:http://blog.taragana.com/index.php/archive/how-to-handle-exceptions-from-static-code-block-in-java 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).