Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Why this property contains a reference to itself?

cause

like image 610
E_d Avatar asked Feb 05 '16 18:02

E_d


People also ask

What happens if exceptions are not handled?

When an exception occurred, if you don't handle it, the program terminates abruptly and the code past the line that caused the exception will not get executed.

What happens when an exception occurs?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

What happens when exception occurs in Java?

When an exception occurs inside a Java method, the method creates an Exception object and passes the Exception object to the JVM (in Java term, the method " throw " an Exception ). The Exception object contains the type of the exception, and the state of the program when the exception occurs.

In which of the following An exception error can occur?

Following are some scenarios where an exception occurs. A user has entered an invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory.


1 Answers

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.

like image 194
wero Avatar answered Oct 13 '22 12:10

wero