以下程序可以正确编译。是什么导致了堆栈溢出错误?异常是如何压入堆栈的?
public class Reluctant {
private Reluctant internalInstance = new Reluctant();
public Reluctant() throws Exception {
throw new Exception("I’m not coming out");
}
public static void main(String[] args) {
try {
Reluctant b = new Reluctant();
System.out.println("Surprise!");
} catch (Exception ex) {
System.out.println("I told you so");
}
}
}
最佳答案
您有一个字段初始化代码,它由 javac 编译器自动添加到构造函数主体中。实际上你的构造函数看起来像这样:
private Reluctant internalInstance;
public Reluctant() throws Exception {
internalInstance = new Reluctant();
throw new Exception("I’m not coming out");
}
因此它递归地调用自身。
关于java - 程序抛出堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30560346/