gpt4 book ai didi

java - 程序抛出堆栈溢出错误

转载 作者:行者123 更新时间:2023-12-02 20:49:02 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com