Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an exception from an enum constructor?

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

like image 253
tekumara Avatar asked Aug 22 '10 23:08

tekumara


2 Answers

Because instances are created in a static initializer, throw an ExceptionInInitializerError instead.

like image 154
tekumara Avatar answered Sep 20 '22 03:09

tekumara


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.

like image 38
silent_h Avatar answered Sep 19 '22 03:09

silent_h