tags:

views:

196

answers:

3

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?

+2  A: 

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?

Jon Skeet
Ah, when debugging I noted that the cause member variable was recursive. However, the getCause() method worked fine. I was catching a org.apache.catalina.connector.ClientAbortException.
Arne Evertsson
I suggest you edit your question then, as it's incorrect :)
Jon Skeet
A: 

That is likely just a bug in the Exception class in question. Report it to the boys of the API in question.

BalusC
See comment on Skeet's answer.
Arne Evertsson
Ah OK. Well, if you want to learn it: the cause of ClientAbortException is that the client aborted the conenction (request). This can happen if the client pressed `Esc` or navigated/tabbed away while the request was still running and the response wasn't completed yet. Easily reproduceable with large response streams (file downloads) or with (pardon me) hogging slow business logic.
BalusC
Yup. Bad question. I've edited it, but can't delete it.
Arne Evertsson
A: 

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.

Nick Fortescue
Even in this case this shouldn't happen as getCause()'s default implementation is `return (cause==this ? null : cause);`
sfussenegger
... and initCause(Throwable) checks for `if (cause == this)`
sfussenegger
See comment on Skeet's answer.
Arne Evertsson