简体   繁体   English

为什么异常的财产“原因”会永远重复?

[英]Why property ''cause" of Exception is repeating forever?

While debugging with eclipse IDE an HttpClientErrorException I noticed that property "cause" contains a reference to the error itself, so I went through and there it was the property "cause" again, and again ... forever. 在使用eclipse IDE调试HttpClientErrorException时,我注意到属性“cause”包含对错误本身的引用,所以我经历了那里,它再次成为属性“cause”,并且再次......永远。

Why this property contains a reference to itself? 为什么这个属性包含对自身的引用?

原因

Throwable declares Throwable声明

private Throwable cause = this;

If the cause is not initialized, either by passing a cause in the constructor or by calling initCause , it will continue to point to this . 如果未初始化原因,无论是通过在构造函数中传递原因还是通过调用initCause ,它将继续指向this Note that consequently getCause is implemented as: 请注意,因此getCause实现为:

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

Update: 更新:

The reason for this design is also explained in Throwable : 这种设计的原因也在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: 为了允许JVM使Throwable对象不可变并安全地重用,例如OutOfMemoryErrors,可响应用户操作而写入的Throwable字段,cause,stackTrace和suppressExceptions遵循以下协议:

1) The fields are initialized to a non-null sentinel value which indicates the value has logically not been set. 1)字段被初始化为非空的标记值,该值表示逻辑上未设置该值。

2) Writing a null to the field indicates further writes are forbidden 2)向字段写入空值表示禁止进一步写入

3) The sentinel value may be replaced with another non-null value. 3)sentinel值可以用另一个非null值替换。

For example, implementations of the HotSpot JVM have preallocated OutOfMemoryError objects to provide for better diagnosability of that situation. 例如,HotSpot JVM的实现具有预分配的OutOfMemoryError对象,以提供对该情况的更好的可诊断性。 These objects are created without calling the constructor for that class and the fields in question are initialized to null. 创建这些对象时不调用该类的构造函数,并将有问题的字段初始化为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. 要支持此功能,添加到Throwable的任何需要初始化为非空值的新字段都需要协调的JVM更改。

Do you have access to source where this Exception was created? 您是否可以访问创建此Exception源?

Looks like the HttpClientErrorException object was created and then its cause field was modified to be the same object, perhaps using initCause . 看起来创建了HttpClientErrorException对象,然后将其cause字段修改为同一个对象,可能使用initCause

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM