views:

59

answers:

2

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

A: 

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

tukushan
Although that's a possible solution I don't think that it would make sense to solve the problem that way.
Johannes Wachter
A: 

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.

Johannes Wachter
If it's bad style to throw Exceptions from a constructor, what do you do when one of the arguments to your constructor is invalid and will prevent your class from functioning? I prefer to fail fast by throwing an exception so I can get a meaningful stack trace. That being said, I agree with you that the OP shouldn't be trying to throw an exception in an **enum's** constructor.
Kirk Woll
@Kirk Woll: I prefer using factory methods that ensure the validity of the parameters. Also I was mainly focussing on checked Exceptions, RuntimeException would be a better way to signal a verification error IMO.
Johannes Wachter
Exclusive use of factory methods for all object instantiation? Oh the poor woebegotten **new** operator. :)
Kirk Woll
@Kirk Woll: No not for all instantiations, but for the once where special validation for the constructor parameters is needed. Normally I'm using the principle of not doing work inside constructors besides assignments, so I'm not programming as fail-fast as you :)
Johannes Wachter
Is there really a difference between throwing an exception from a factory method versus a constructor? You say tomato I say tomatoe
matt b