在Java中设置异常原因 [英] Setting an exception cause in Java
问题描述
我看到捕获了一个可以打印e.getCause()
的异常,尽管它总是null
.
I can see on catching an exception that I can print e.getCause()
, though it is always null
.
我是否需要将其设置在某个地方,或者缺少将原因设置为null的东西?
Do I need to set it somewhere, or is something missing which is setting the cause to null?
推荐答案
异常具有属性message
和cause
.该消息是一种描述,或多或少准确地告诉人类读者出了什么问题. cause
有所不同:它是另一个(嵌套的)Throwable
(如果有).
An Exception has the attributes message
and cause
. The message is a description, telling a human reader more or less exactly, what went wrong. The cause
is something different: it is, if available, another (nested) Throwable
.
如果我们使用这样的自定义异常,通常会使用该概念:
The concept is often used if we use custom exceptions like this:
catch(IOException e) {
throw new ApplicationException("Failed on reading file soandso", e);
// ^ Message ^ Cause
}
针对 djangofan的评论:
标准是嵌套表达式(原因)也将打印其堆栈跟踪信息.
The standard is that the nested expression (the cause) is printed with its stack trace too.
运行这个小应用程序
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
两个消息都包括在内.
这篇关于在Java中设置异常原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!