2013-04-21 87 views
2

我試圖讓一個拋出的異常的情況下,以顯示它的原因:顯示異常的原因

if (throwable instanof MyException) 
    //Do something here.. 
} else if (throwable instanceof Exception) { 
    if (throwable.getCause() != null) { 
     //Show the cause here .. 
     // throwable.getCause().getLocalizedMessage() 
    } 
} 

我使用getCause()而表達守望表演時總是爲Cause一個null值它有一個非空值。

enter image description here

如何獲得的原因是什麼?

+0

Try * throwable.getMessage()* – 2013-04-21 22:53:30

回答

3

getCause返回null如果causethis是相同的。下面是從JDK片段:

public synchronized Throwable getCause() { 
    return (cause==this ? null : cause); 
} 

在你的情況,是UsernameNotFoundException你要找的例外呢?

+0

是的。所以如果原因是空的,這意味着我不需要再進一步......謝謝。 – 2013-04-21 22:46:40

+1

正確。 Apache Commons ExceptionUtils http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/exception/ExceptionUtils.html提供了一些用於處理異常的好幫手方法。 – 2013-04-21 22:49:30

+0

這非常有幫助,謝謝。 – 2013-04-21 22:52:32