根据 JLS:如果命名类的实例变量初始化程序或实例初始化程序可以抛出已检查的异常类,则这是编译时错误,除非该异常类或其超类之一在每个构造函数的 throws 子句中显式声明它的类并且该类至少有一个显式声明的构造函数。
所以如果我这样做 -
class A{
{
throw new FileNotFoundException();
}
public A() throws IOException{
// TODO Auto-generated constructor stub
}
}
这给出了编译时错误“初始化程序必须正常完成”
尽管
class A{
{
File f=new File("a");
FileOutputStream fo=new FileOutputStream(f);
fo.write(3);
}
public A() throws IOException{
// TODO Auto-generated constructor stub
}
}
此代码不显示任何编译时错误。为什么即使我在构造函数中声明了 throws 子句,前面的代码也无法编译?