I'm declaring a constant object in my class definition, whose
constructor throws an exception. Note that the exception never actually
gets thrown - my argument ensures that.
Apparently, I can't use try-catch blocks outside a method, so I can't
initialize this value in the class declaration. But if I don't
initialize it there, I can't declare it final.
Does this just mean I can't initialize final variables with
exception-throwing constructors, or is there a solution?
--cb
Tom Hawtin - 10 May 2007 09:00 GMT
> I'm declaring a constant object in my class definition, whose
> constructor throws an exception. Note that the exception never actually
[quoted text clipped - 3 lines]
> initialize this value in the class declaration. But if I don't
> initialize it there, I can't declare it final.
private static final MyClass thing;
static {
try {
thing = new MyClass();
} catch (SomeException exc) {
throw new Error();
}
}
or
private static final MyClass thing = makeThing();
private static MyClass MakeThing() {
try {
return new MyClass();
} catch (SomeException exc) {
throw new Error();
}
}
Tom Hawtin