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

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


因此它以递归方式调用自己。

07-26 03:58