six*_*ude 5 java static constructor exception
我有一个静态setter用于设置MyClass的所有实例:
public class MyClass {
....
protected static final Setter setter = new Setter();
...
}
Run Code Online (Sandbox Code Playgroud)
但是这不会编译,因为setter构造函数会抛出异常:
public class Setter {
public Setter() throws FileNotFoundException {
....
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
Bal*_*usC 17
该ExceptionInInitializerError设计出于这样的目的.以下是链接Javadoc的相关内容:
表示静态初始化程序中发生意外异常的信号.
ExceptionInInitializerError抛出An 表示在评估静态初始化程序或静态变量的初始化程序期间发生异常.
将赋值包装在静态初始化程序块中并相应处理.
public class MyClass {
protected static final Setter setter;
static {
try {
setter = new Setter();
} catch (FileNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4037 次 |
| 最近记录: |