在java中设置异常原因 [英] Setting Exception cause in java

查看:300
本文介绍了在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?

推荐答案

异常具有消息原因的属性。消息是一个描述,告诉人类读者或多或少的确切,出了什么问题。 导致有所不同:它是(如果有的话)另一个(嵌套) 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
}

编辑 - 响应@ djangofans评论。

Edit - in response to @djangofans comment.

标准是嵌套表达式(原因)也打印它的堆栈跟踪。

The standard is that the nested expression (the cause) is printed with it's 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆