【发布时间】:2011-04-27 07:09:11
【问题描述】:
我可以看到我可以打印e.getCause() 的异常,尽管它始终是null。
我需要在某处设置它,还是缺少将原因设置为 null 的东西?
【问题讨论】:
我可以看到我可以打印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
这两条消息都包含在内。
【讨论】:
Exception 类的构造函数采用cause Throwable。您需要调用这些构造函数或为调用这些超级构造函数的自定义异常类提供构造函数。
【讨论】:
原因通常在异常的构造函数中设置。看public Exception(String message, Throwable cause)。
如果构造函数中没有设置,可以调用initCause()。
【讨论】:
getCause - 如果原因不存在或未知,则返回此 throwable 的原因或 null。 (原因是导致这个 throwable 被抛出的 throwable。)
阅读 Java 文档:getCause
【讨论】:
如果你只是想摆脱 null 作为原因 然后覆盖扩展 Exception 类的 CustomException 类的 toString() 方法。
public class CustomException extends Exception {
private static final long serialVersionUID = 9355648L;
public CustomException(String message, Throwable cause) {
super(message, cause);
}
@Override
public String toString() {
return "Business Exception";
}
}
和
throw new CustomException("Stopping further processing.", new CustomException("stale message"));
输出如下
Stopping further processing. Cause : Business Exception
用于后续的 catch 块。
} catch (CustomException ce) {
System.out.print(ce.getMessage());
System.out.println(" Cause : " + ce.getCause());
}
【讨论】: