10

在调试器中查看 Java 中的异常时,您经常会看到原因是无限递归到自身的(我假设它是无限的)。

例如:

Exception1, 
  Caused by -> Exception2 
     Caused by -> Exception2
        Caused by -> Exception2 

为什么是这样?

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

4

1 回答 1

19

查看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;

所以我猜你看到的是一个异常,它是在没有使用一个有原因的构造函数的情况下创建的。

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

  414       public synchronized Throwable getCause() {
  415           return (cause==this ? null : cause);
  416       }
于 2012-06-29T13:41:33.640 回答