我可以在捕获异常时看到我可以打印 e.getCause()
,尽管它总是 null
。
我需要在某处设置它,还是缺少将原因设置为 null 的东西?
最佳答案
异常具有 message
和 cause
属性。该消息是一个描述,或多或少准确地告诉人类读者,出了什么问题。 cause
是不同的:如果可用,它是另一个(嵌套的)Throwable
。
如果我们使用这样的自定义异常,通常会使用这个概念:
catch(IOException e) {
throw new ApplicationException("Failed on reading file soandso", e);
// ^ Message ^ Cause
}
标准是嵌套表达式(原因)也与其堆栈跟踪一起打印。
运行这个小应用程序
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 - 在 Java 中设置异常原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5800629/