2012-06-29 76 views
6

在調試器中查看Java中的異常時,您經常會看到原因無限遞歸(我認爲它是無限的)。什麼導致異常中的遞歸原因?

e.g:

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

這是爲什麼?

注意:這是在調試器中查看代碼的情況,在這種情況下是Eclipse。

+1

我從來沒有見過那個......我想如果沒有細節就很難說 – hage

+2

你有任何你所指的代碼?它更清晰,如果你有錯誤 – vandershraaf

+0

的代碼+堆棧跟蹤請詳細說明,也許代碼? –

回答

15

望着source code of 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  } 
+4

似乎像一個等待發生的錯誤,如果任何時候有時間旅行。如果一個例外時光倒流並導致其自身發生,該怎麼辦? _Dun dun dunnnnn!_ – yshavit

+0

我覺得這是一個有趣的問題。我經常看到底層庫引發的異常,這些異常將自己當作自己的原因,從而創建了一個無限循環。爲什麼要這樣做? –

+2

這是一個有趣的例子,說明API的隱藏和封裝部分可能會給開發人員帶來問題(這裏有人試圖將2個值打包到一個字段中,也許出於某種性能原因)。我經常發現自己在IntelliJ中擴展了原因,並且在十個關注WTF的級別之後...... – csharpfolk

相關問題