我有一个问题,如果在创建枚举常量的过程中发生错误,会发生什么?例如,我有一个枚举
Enum statuses{
OPEN(1, init(1)), CLOSE(2, init(2));
private final int value;
private final int internalValue;
statuses(int v, int intv){
this.value = v;
this.internalValue = intv;
}
static int init(int value){
return get a value from db and return it;
}
}现在,如果init方法中出现错误,即连接丢失,将初始化枚举类型还是其他什么?我是否应该处理init方法中可能的错误并返回默认值,然后检查它是否为re init enum常量?
发布于 2013-05-07 04:36:08
Java enum只是一个带有一些自动生成代码的类。所有枚举条目都是在加载类时启动的public final static字段。如果在初始化过程中抛出了异常,你将无法使用枚举:每次尝试访问它都会抛出异常。
顺便说一句,使用本应在枚举初始化中抛出异常的代码是一种不好的做法。您应该编写硬编码的枚举,或者使这种初始化变得懒惰,或者将枚举转换为普通类。
https://stackoverflow.com/questions/16406762
复制相似问题