2013-04-21 79 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