java 如何从枚举构造函数抛出异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3543903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to throw an exception from an enum constructor?
提问by tekumara
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
未处理的异常类型 IOException
回答by tekumara
Because instances are created in a static initializer, throw an ExceptionInInitializerError instead.
因为实例是在静态初始化器中创建的,所以抛出一个 ExceptionInInitializerError 代替。
回答by silent_h
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.
当我为此创建一个快速测试时,我发现抛出的异常不是我的,而是一个 ExceptionInInitializerError。
Maybe this is dumb, but I think it's a fairly valid scenario for wanting to throw an exception in a static initializer.
也许这是愚蠢的,但我认为这是想要在静态初始化程序中抛出异常的一个相当有效的场景。
回答by Johannes Wachter
That scenario cannot work.
这种情况是行不通的。
You are trying to throw a checked Exceptionfrom the constructor.
您正试图Exception从构造函数中抛出一个检查。
This constructor is called by the INSTANCEenum entry declaration, so the checked exception cannot be handled correctly.
这个构造函数被INSTANCE枚举入口声明调用,所以无法正确处理checked异常。
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 IOExceptionI assume that you want to initialize something from a file, so you should perhaps consider this article on dynamic enums.
另外,如果你想抛出一个IOException我假设你想从文件中初始化一些东西,所以你也许应该考虑这篇关于动态枚举的文章。

