Java: exception-throwing class?
The throws
keyword cannot be applied at class level, only at the method level.
It is a compile-time error for a class initializer ("static block") to terminate with a checked exception.
If a class initializer throws an unchecked exception, the first attempt to initialize the class will raise an ExceptionInInitializeError
. Any subsequent attempts to use the class will cause a NoClassDefFoundError
. If you really want to use an exception, throw something like a RuntimeException
in the initializer.
However, the approach shown in the question—setting a flag when the class is initialized correctly—might actually be a better one for many applications. More specifically, I'd say that unless you want the whole program to terminate when there's a initialization failure, use a flag. Just remove the "throws" clause from the class declaration, because that isn't a legal syntax.