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
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.
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.