在java中设置exception原因
我可以看到捕获exception,我可以打印e.getCause()
,虽然它总是为null
。
我是否需要将其设置在某个地方,或者是否缺少将原因设置为null?
Exception具有属性message
和cause
。 该消息是一种描述,或多或少地告诉人类读者,出了什么问题。 cause
是不同的:如果可用的话,它是另一个(嵌套的) Throwable
。
如果我们使用这样的自定义exception,则经常使用该概念:
catch(IOException e) { throw new ApplicationException("Failed on reading file soandso", e); // ^ Message ^ Cause }
编辑 – 响应@djangofans评论。
标准是嵌套表达式(原因)也用它的堆栈跟踪打印。
运行这个小应用程序
public class Exceptions { public static void main(String[] args) { Exception r = new RuntimeException("Some message"); throw new RuntimeException("Some other message", r); } }
将输出
Exception in thread "main" java.lang.RuntimeException: Some other message at Exceptions.main(Exceptions.java:4) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Caused by: java.lang.RuntimeException: Some message at Exceptions.main(Exceptions.java:3) ... 5 more
两条消息都包含在内。
原因通常在exception的构造函数中设置。 查看公共exception(String message,Throwable cause) 。
如果未在构造函数中设置,则可以调用initCause() 。
class Exception
具有cause
Throwable成为cause
构造函数。 您需要调用那些构造函数或为您调用这些超级构造函数的自定义exception类提供构造函数。
getCause – 返回此throwable的原因,如果原因不存在或未知,则返回null。 (原因是导致抛出此抛掷物的抛掷物。)
阅读Java doc: getCause