我很想知道抛出已检查异常的字段初始化。例如,
public static final FileOutputStream fileOut1 = new FileOutputStream(new File("test.txt"));
这给出了编译错误“未处理的异常类型FileNotFoundException”。我知道我可以使用下面的静态初始化程序块,但有更优雅的方法吗?
public static final FileOutputStream fileOut2;
static {
FileOutputStream temp = null;
try {
temp = new FileOutputStream(new File("test.txt"));
} catch (FileNotFoundException e) {
//log some warnings, maybe
}finally{
fileOut2= temp;
}
}
非静态实例字段怎么样
public final FileOutputStream fileOut3 = new FileOutputStream(new File("test.txt"));
这个抛出一个非常奇怪的编译错误“默认构造函数无法处理由隐式超级构造函数抛出的异常类型FileNotFoundException。必须定义一个显式构造函数”。同样,我可以通过在初始化程序块或内部构造函数中进行初始化来解决它。但我很好奇“ ..隐式超级构造函数抛出的FileNotFoundException ... ”意味着什么。初始化语句抛出的异常是否会以某种方式传播到超级构造函数?我绝对不能做以下因为超级电话必须是第一个声明
public final FileOutputStream fileOut3 = new FileOutputStream(new File("test.txt"));
public MyClassFoo(){
try{
super();//compile error
}catch(Exception e){
}
}
如果我抛出FileNotFoundException,编译错误会消失,但有没有办法捕获初始化语句抛出的异常而不诉诸初始化程序块或将语句带入构造函数本身?
public MyClassFoo() throws FileNotFoundException{
}
答案 0 :(得分:3)
关于静态字段。我要做的第一件事是在初始化类时避免打开文件流。这应该在方法中完成。它应该确保流关闭。也就是说,您可以通过委托方法来避免静态块:
private static final FileOutputStream fileOut1 = openFileStream();
该方法将处理异常。
关于实例字段,干净的方法是从构造函数初始化它们,或者使用与上面相同的技术。