How can I throw an exception from an enum constructor? eg:
public enum RLoader {
INSTANCE;
private RLoader() throws IOException {
....
}
}
produces the error
Unhandled exception type IOException
Because instances are created in a static initializer, throw an ExceptionInInitializerError instead.
I have a case where I want to use enums as keys in some settings classes. The database will store a string value, allowing us to change the enum constants without having to udpate the database (a bit ugly, I know). I wanted to throw a runtime exception in the enum's constructor as a way to police the length of the string argument to avoid hitting the database and then getting a constraint violation when I could easily detect it myself.
public enum GlobalSettingKey {
EXAMPLE("example");
private String value;
private GlobalSettingKey(String value) {
if (value.length() > 200) {
throw new IllegalArgumentException("you can't do that");
}
this.value = value;
}
@Override
public String toString() {
return value;
}
}
When I created a quick test for this, I found that the exception thrown was not mine, but instead was an ExceptionInInitializerError.
Maybe this is dumb, but I think it's a fairly valid scenario for wanting to throw an exception in a static initializer.
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