【发布时间】:2015-07-31 02:13:05
【问题描述】:
根据 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 子句,前面的代码还是编译不出来?
【问题讨论】:
-
你告诉初始化程序块抛出无条件异常,你还能期待什么?
标签: java