什么原因导致异常中的递归原因?

Ban*_*San 9 java exception

在调试器中查看Java中的异常时,您经常会看到原因无限递归(我认为它是无限的).

例如:

Exception1, 
  Caused by -> Exception2 
     Caused by -> Exception2
        Caused by -> Exception2 
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

注意:这是在查看调试器中的代码时,在这种情况下是Eclipse.

sud*_*ode 17

查看Throwable源代码:

  187       /**
  188        * The throwable that caused this throwable to get thrown, or null if this
  189        * throwable was not caused by another throwable, or if the causative
  190        * throwable is unknown.  If this field is equal to this throwable itself,
  191        * it indicates that the cause of this throwable has not yet been
  192        * initialized.
  193        *
  194        * @serial
  195        * @since 1.4
  196        */
  197       private Throwable cause = this;
Run Code Online (Sandbox Code Playgroud)

所以我猜你所看到的是一个Exception,它是在不使用其中一个构造函数的情况下创建的.

您将在调试器中看到这一点,但getCause负责不返回递归引用:

  414       public synchronized Throwable getCause() {
  415           return (cause==this ? null : cause);
  416       }
Run Code Online (Sandbox Code Playgroud)

  • 看起来像一个等待发生的错误,如果有人发明了时间旅行.如果异常及时发生并导致自身发生怎么办?_Dun dun dunnnnn!_ (5认同)
  • 这是一个有趣的例子,说明API的隐藏和封装部分如何为开发人员带来问题(这里有人试图将2个值打包到一个字段中,可能出于某些性能原因).我经常发现自己在IntelliJ中扩展了`cause`es,并且在10个级别之后想知道WTF ...... (2认同)