简体   繁体   English

如何从枚举构造函数中抛出异常?

[英]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 未处理的异常类型IOException

因为实例是在静态初始化程序中创建的,所以抛出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. 我想在枚举的构造函数中抛出一个运行时异常,作为一种警告字符串参数长度的方法,以避免命中数据库,然后在我可以自己轻松检测到它时获得约束违规。

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. 也许这是愚蠢的,但我认为这是一个非常有效的场景,想要在静态初始化器中抛出异常。

That scenario cannot work. 那种情况不起作用。

You are trying to throw a checked Exception from the constructor. 您正在尝试从构造函数中抛出已检查的Exception

This constructor is called by the INSTANCE enum entry declaration, so the checked exception cannot be handled correctly. 此构造函数由INSTANCE枚举条目声明调用,因此无法正确处理已检查的异常。

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 . 此外,如果你想抛出一个IOException我假设你想从文件中初始化一些东西,所以你应该考虑动态枚举这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM