程序抛出堆栈溢出错误

Program throws Stack Overflow Error

以下程序编译正确。是什么导致堆栈溢出错误?异常是如何压入堆栈的?

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");
        }
    }
}

您的 main 方法中的这一行导致无限递归:

Reluctant b = new Reluctant();

每次您尝试创建 Reluctant 的实例时,您要做的第一件事就是创建另一个实例,这会创建另一个实例,这会创建另一个实例,这...您明白了。

瞧,堆栈溢出!

你有一个无限循环。 Reluctant class 的每个实例都会在 internalInstance 声明中实例化另一个 Reluctant 对象。因此,当您在 main 方法上实例化第一个 Reluctant 对象时,程序会一遍又一遍地创建一个又一个实例,直到堆栈溢出。

替换此行。-

private Reluctant internalInstance = new Reluctant();

对于

private Reluctant internalInstance;

您有一个字段初始化代码,它由 javac 编译器自动添加到构造函数主体中。实际上你的构造函数看起来像这样:

private Reluctant internalInstance;

public Reluctant() throws Exception {
    internalInstance = new Reluctant();
    throw new Exception("I’m not coming out");
}

所以递归调用自己