java - 在 Java 中设置异常原因

标签 java exception

我可以在捕获异常时看到我可以打印 e.getCause(),尽管它总是 null

我需要在某处设置它,还是缺少将原因设置为 null 的东西?

最佳答案

异常具有 messagecause 属性。该消息是一个描述,或多或少准确地告诉人类读者,出了什么问题。 cause 是不同的:如果可用,它是另一个(嵌套的)Throwable

如果我们使用这样的自定义异常,通常会使用这个概念:

catch(IOException e) {
  throw new ApplicationException("Failed on reading file soandso", e);
  //                              ^ Message                        ^ Cause
}

回应djangofan's comment :

标准是嵌套表达式(原因)也与其堆栈跟踪一起打印。

运行这个小应用程序

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/

相关文章:

java - Java 异常构造函数是否必需?

java - 类未发现异常?

java - Autowiring Spring 父类(super class)

java - 读取 firebase DB 后如何更改 ListView 上的颜色和字体

java - 无法将 View.getTag 转换为 ArrayList<String>

python - 如何处理列表推导中的异常?

c# - Entity Framework 异常 : New transaction is not allowed because there are other threads running in the session

java - 循环重写的简单方法

java - 为什么我在 JavaFX 上得到 “Not on FX application thread”?

python - 使用APScheduler时如何处理异常?