How to throw an exception from an enum constructor?

前端 未结 3 1381
-上瘾入骨i
-上瘾入骨i 2020-12-11 15:31

How can I throw an exception from an enum constructor? eg:

public enum RLoader {
  INSTANCE;
  private RLoader() throws IOException {
   ....
  }
}


        
相关标签:
3条回答
  • 2020-12-11 15:38

    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.

    0 讨论(0)
  • 2020-12-11 15:42

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

    0 讨论(0)
  • 2020-12-11 15:49

    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 讨论(0)
提交回复
热议问题