面对 java.lang.StackOverflowError 从构造函数中抛出未经检查的异常

Facing java.lang.StackOverflowError on throwing unchecked exception from constructor

我正在尝试 运行 下面的代码示例,但出现 Whosebug 错误。它似乎陷入了无限循环。任何人都可以帮助我了解这里发生了什么吗?

请在下面找到代码片段

public class ConstructorExample {

    private ConstructorExample c1 = new ConstructorExample();

    public ConstructorExample(){
        throw new RuntimeException();
    }

    public static void main(String[] str){
        ConstructorExample c = new ConstructorExample();
    }
}

您有会员 private ConstructorExample c1 = new ConstructorExample(); 在 ConstructorExample class.

当您实例化 ConstructorExample 的第一个实例时,JVM 会为该 ConstructorExample 分配内存,然后尝试实例化第一个成员 c1。此实例化从为另一个 ConstructorExample 实例分配内存开始,依此类推。

此外,运行时异常无关紧要,因为成员初始化程序在构造函数之前执行。

符合预期。 ConstructorExample 的实例创建尝试从 main 方法开始,在调用构造函数之前初始化实例变量。

private ConstructorExample c1 = new ConstructorExample();

然后再次重复循环并继续分配越来越多的内存导致堆栈溢出,甚至没有完成完全创建单个实例。