Blog

Silent Exceptions in static initializers

I have recently seen silent exceptions in static initializers…I recommend that you correct the code if you encounter them

Example of silent exception in static initializer…
static {
try {
DOCUMENT_FACTORY = DocumentBuilderFactory.newInstance()
DOCUMENT_BUILDER = DOCUMENT_FACTORY.newDocumentBuilder();
TRANSFORMER = TransformerFactory.newInstance().newTransformer();
} catch (Exception ex) {
// Exceptions ignored.
}
}

In this example DOCUMENT_FACTORY.newDocumentBuilder() can throw a ParserConfigurationException, leaving DOCUMENT_BUILDER null.
And TransformerFactory.newInstance().newTransformer() can throw a TransformerConfigurationException. Leaving TRANSFORMER null.

Every usage of DOCUMENT_BUILDER and TRANSFORMER within this class assumes that the variable is properly set, meaning that if the exception in the static initializer is ignored the code will eventually fail with a null pointer exception.

Clearly it is not the author’s intent to ignore this exception but what can you do with an exception in a static initializer?
This example is from a utility class (All static methods - Which generally indicates procedural design - yuck!) so this initialization cannot be moved to the object constructor, and you cannot declare that the static initializer throws an exception so what can you do?

Simply throw a RuntimeException from the catch clause.

I submit that the desired implementation is as follows:
static {
DOCUMENT_FACTORY = DocumentBuilderFactory.newInstance()
try {
DOCUMENT_BUILDER = DOCUMENT_FACTORY.newDocumentBuilder();
TRANSFORMER = TransformerFactory.newInstance().newTransformer();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}

In this case the try block is around the only two lines of code that throw a checked exception. I believe making the scope the try block too broad, or the type of the exception in the catch block too broad can have unintended consequences in most cases (Probably not in this case.)

Throwing a RuntimeException means that execution will terminate early with the appropriate message rather than terminating later with a NullPointerException when DOCUMENT_BUILDER or TRANSFORMER is used.

Feedback, comments, and questions are welcome.
By Dale Lotts on Oct 20 '06