How to throw an exception from an enum constructor?

前端 未结 3 1389
-上瘾入骨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: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.

提交回复
热议问题