gpt4 book ai didi

java - 为什么属性 '' 导致“异常”永远重复?

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:30 26 4
gpt4 key购买 nike

在使用 eclipse IDE 调试 HttpClientErrorException 时,我注意到属性“cause”包含对错误本身的引用,所以我仔细检查了一下,发现它又是属性“cause”,一次又一次……永远。

为什么这个属性包含对自身的引用?

cause

最佳答案

Throwable 声明

private Throwable cause = this;

如果 cause 没有被初始化,无论是通过在构造函数中传递一个 cause 还是通过调用 initCause,它都会继续指向 this。请注意,因此 getCause 实现为:

public synchronized Throwable getCause() {
return (cause==this ? null : cause);
}

更新:

这样设计的原因在Throwable中也有说明:

To allow Throwable objects to be made immutable and safely reused by the JVM, such as OutOfMemoryErrors, fields of Throwable that are writable in response to user actions, cause, stackTrace, and suppressedExceptions obey the following protocol:

1) The fields are initialized to a non-null sentinel value which indicates the value has logically not been set.

2) Writing a null to the field indicates further writes are forbidden

3) The sentinel value may be replaced with another non-null value.

For example, implementations of the HotSpot JVM have preallocated OutOfMemoryError objects to provide for better diagnosability of that situation. These objects are created without calling the constructor for that class and the fields in question are initialized to null. To support this capability, any new fields added to Throwable that require being initialized to a non-null value require a coordinated JVM change.

关于java - 为什么属性 '' 导致“异常”永远重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230698/

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