我有一个用于设置 MyClass 的所有实例的静态 setter :
public class MyClass {
....
protected static final Setter setter = new Setter();
...
}
然而,由于 setter 构造函数抛出异常,因此无法编译:
public class Setter {
public Setter() throws FileNotFoundException {
....
}
}
我该如何解决这个问题?
最佳答案
ExceptionInInitializerError
正是为此目的而设计的。这是链接的 Javadoc 中的相关引用:
Signals that an unexpected exception has occurred in a static initializer. An
ExceptionInInitializerError
is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
将赋值包装在静态初始化 block 中并进行相应处理。
public class MyClass {
protected static final Setter setter;
static {
try {
setter = new Setter();
} catch (FileNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
}
关于Java:创建其构造函数可能引发异常的静态类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3247055/