开发者

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


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.


That scenario cannot work.

You are trying to throw a checked Exception from the constructor.

This constructor is called by the INSTANCE enum entry declaration, so the checked exception cannot be handled correctly.

Also it is in my opinion it's bad style to throw Exceptions from a constructor, as a constructor normally shouldn't do any work and especially not create errors.

Also if you want to throw an IOException I assume that you want to initialize something from a file, so you should perhaps consider this article on dynamic enums.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜