根据 JLS:如果命名类的实例变量初始值设定项或实例初始值设定项可以抛出已检查的异常类,则这是一个编译时错误,除非该异常类或其父类(super class)之一在 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 子句,之前的代码仍无法编译?
最佳答案
应该有一些条件可以让初始化程序真正完成而没有任何异常。
在您的情况下,这是不可能发生的。
尝试:
if(/*condition-to-fail*/) {
/*Not always, only when something is wrong. Compiler knows that.*/
throw new FileNotFoundException();
}
更新:
下面的语句实际上是在抛出异常。
throw new FileNotFoundException();
因此,在没有任何条件的情况下,您的程序执行总是到此结束。
虽然在下面-
FileOutputStream fo = new FileOutputStream(f);
构造函数 FileOutputStream(File)
并不总是抛出该异常。
public FileOutputStream(File file) throws FileNotFoundException
中的 throws 子句只是说它可能会抛出该异常,并且只有在运行时找不到文件时才会抛出异常。
关于java - 检查异常和初始化程序 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15042236/