我已经很清楚实例初始化器不能抛出异常,因为它是对象初始化的一部分,开发人员无法控制这个过程。 This post有同样的想法。
不过,我看过Bill Venners的一篇关于java中对象初始化的文章,其中有一段引用如下:
The code inside an instance initializer may not return. Except in the case of anonymous inner classes, an instance initializer may throw checked exceptions only if the checked exceptions are explicitly declared in the throws clause of every constructor in the class. Instance initializers in anonymous inner classes, on the other hand, can throw any exception. Please click here for original post.
好像说实例初始化器可以抛出异常。如果我的理解不正确,这里的任何人都可以向我解释或纠正我。
最佳答案
实例初始化器可以抛出已检查的异常,但如果它们抛出,则类构造函数必须声明它们。例如,这段代码是合法的:
import java.io.*;
public class MyClass {
PrintStream stream;
{
stream = new PrintStream("/tmp/file.txt");
}
public MyClass() throws FileNotFoundException {
}
}
但是,如果构造函数中省略了 throws
子句,或者添加了另一个不包含该子句的构造函数,则不会编译,因为 PrintStream
构造函数抛出 FileNotFoundException
。
关于java - 实例初始化程序可以抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8352621/