Arne Evertsson
Arne Evertsson

Reputation: 19827

Why is exception.getCause() == exception?

I made a mistake when asking this question by thinking that the value of the member variable cause would be returned as the result of a call to getCause() in org.apache.catalina.connector.ClientAbortException. That obviously isn't the case. The real cause is returned.

Looking at the source of Throwable I can see that it sets cause = this to indicate that the cause has yet to be set. This was a bad question but I did learn something from asking it.

Original question below:

Sometimes when you catch exceptions, the getCause() will return the exception object itself, making it recursive. Why doesn't getCause() return null?

Upvotes: 5

Views: 6384

Answers (2)

Nick Fortescue
Nick Fortescue

Reputation: 44183

Can you give an example of when this occurs? The only way I can see that it would happen is if the author called initCause() with the exception itself after construction, and this is very bad practive. I've never seen it.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502196

getCause() should never return itself unless it's been overridden - if you look at the code for getCause() it explicitly returns null if the cause variable is the same as the throwable you're calling it on.

Which exceptions are you running into which do return the same exception again?

Upvotes: 5

Related Questions