简体   繁体   中英

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?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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