Why property ''cause" of Exception is repeating forever?

∥☆過路亽.° 提交于 2020-01-03 12:43:32

问题


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.

Why this property contains a reference to itself?


回答1:


Throwable declares

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. Note that consequently getCause is implemented as:

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

Update:

The reason for this design is also explained in 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.




回答2:


Do you have access to source where this Exception was created?

Looks like the HttpClientErrorException object was created and then its cause field was modified to be the same object, perhaps using initCause.



来源:https://stackoverflow.com/questions/35230698/why-property-cause-of-exception-is-repeating-forever

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!