There are a few problems with your code:
You have the exception name incorrect. The exception you are trying to throw is called ExceptionInInitializerError
not ExceptionInitializerError
. That is one reason why it won't compile.
Never1 throw Error
or subclasses of Error
.
If you need to throw an unchecked exception, throw RuntimeException
. Or better still, pick something more specific or define and use your own custom (unchecked) exception class.
This should (probably) be a static
initializer block, not a plain (instance) initializer. You want this code to be executed once ... not every time a SomeTest
instance is created.
Bailing out of a static
initializer block is something you want to avoid. It basically leaves you with a dead application ... because the enclosing class and any classes that depend on it become uninitializable.
Having said that, the following might be a more appropriate structure:
static {
BlahType tmp = null;
label: {
for (...) {
if (...) {
tmp = ...;
break label;
}
}
throw new SomeException(...);
}
FINAL_VAR = tmp;
}
Note that we need to do the final assignment to FINAL_VAR
in a way that ensures that it is definitely assigned. (My guess is that is a second reason you were getting compilation errors.)
And a more natural way to write the above would be:
static {
BlahType tmp = null;
for (...) {
if (...) {
tmp = ...;
break;
}
}
if (tmp == null) {
throw new SomeException(...);
}
FINAL_VAR = tmp;
}
1 - Maybe a bit too strong. I would say that throwing AssertionError
is OK ... assuming that you intend for it never be caught / recovered from. In this case, recovery is moot anyway.