I have a static setter that is used to set all instances of MyClass:
public class MyClass {
....
protected static final Setter setter = new Setter();
...
}
However this does not compile since the setter constructor throws an exception:
public class Setter {
public Setter() throws FileNotFoundException {
....
}
}
How can I work around this?
The ExceptionInInitializerError
is designed for exactly this purpose. Here's a cite of relevance from the linked Javadoc:
Signals that an unexpected exception has occurred in a static initializer. An
ExceptionInInitializerError
is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
Wrap the assignment in a static initializer block and handle accordingly.
public class MyClass {
protected static final Setter setter;
static {
try {
setter = new Setter();
} catch (FileNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With