I find myself choosing between the two following design patterns a lot:
static {
try {
foo();
}
catch(Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
and
TheConstructor() throws SomeException {
if(alreadyInited) {
return;
}
alreadyInited = true;
foo();
}
The problem is I really do want to initialize stuff once per class - so statically, I think - such as setting up a logger, loading some map from a file, etc. - and I really do want the program to halt if this operation fails. Both of these design patterns seem kludgey (the first one more obviously so), so I'm wondering if there's a better way to do this.
Is allowing exceptions in static class constructors to escape a proper design pattern?
I would say No.
First, wrappering a checked exception in that context means that if something goes wrong you will get a class initialization failure.
An exception that propagates out of the class initalizer cannot be caught and handled directly.
An uncaught exception during class initialization is not recoverable. Even if you could catch and handle the exception, the class and (I think) all others that depend on it / they will be left in a state where they cannot be initialized, and hence cannot be used. That's effectively "game over" for (at least) the classloader, and possibly the entire JVM.
The bigger picture is that this probably represents an inappropriate use of statics. There are better ways to handle this problem; e.g.
Do the initialization using an explicit call (in a place where you can catch and handle the exception), rather than relying on class initialization.
Get rid of the static (and potentially the singleton class that wraps it) and use dependency injection.