tekumara
tekumara

Reputation: 8807

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

Upvotes: 20

Views: 18438

Answers (3)

tekumara
tekumara

Reputation: 8807

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

throw new ExceptionInInitializerError();

Upvotes: 23

silent_h
silent_h

Reputation: 153

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.

Upvotes: 4

Johannes Wachter
Johannes Wachter

Reputation: 2735

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.

Upvotes: 1

Related Questions