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).
2 thoughts on “How not to handle exceptions from static code block in Java”
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.