You can do this but you need to exit the static block by throwing an exception - you can rethrow the exception that was caught or a new one. Generally this exception must be a RuntimeException
. You really should not catch a generic Exception
but more specific exception(s) that might be thrown from within your try
block. Finally, if a static initializer throws an exception then it will render the class unusable during that specific run because the JVM will only attempt to initialize your class once. Subsequent attempts to use this class will result in another exception, such as NoClassDefFoundError
.
So, to work, your initializer should read something like this:
static {
try {
...
} catch (Exception e) {
e.PrintStackTrace();
throw new InitializationFailedException("Could not init class.", e);
}
}
Assuming that InitializationFailedException
is a custom RuntimeException
, but you could use an existing one.