如何从枚举构造函数抛出异常?
如何从枚举构造函数抛出异常?例如:
public enum RLoader {
INSTANCE;
private RLoader() throws IOException {
....
}
}
产生错误
未处理的异常类型 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于实例是在静态初始化程序中创建的,因此应抛出 ExceptionInInitializerError 。
Because instances are created in a static initializer, throw an
ExceptionInInitializerError
instead.我有一个例子,我想在某些设置类中使用枚举作为键。数据库将存储一个字符串值,允许我们更改枚举常量,而不必更新数据库(我知道有点难看)。我想在枚举的构造函数中抛出一个运行时异常,作为监管字符串参数长度的一种方式,以避免访问数据库,然后在我自己可以轻松检测到它时发生约束冲突。
当我为此创建一个快速测试时,我发现抛出的异常不是我的,而是 ExceptionInInitializerError。
也许这很愚蠢,但我认为对于想要在静态初始化程序中抛出异常来说,这是一个相当有效的场景。
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.
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.
这种情况行不通。
您试图从构造函数中抛出已检查的
Exception
。该构造函数由
INSTANCE
枚举条目声明调用,因此无法正确处理已检查的异常。另外,在我看来,从构造函数抛出异常是不好的风格,因为构造函数通常不应该做任何工作,尤其是不创建错误。
另外,如果您想抛出
IOException
我假设您想从文件中初始化某些内容,所以您也许应该考虑 动态枚举。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.