在java中为什么自定义异常也应该有一个构造函数,其中arg为“Throwable cause” [英] In java why custom exceptions should also have a constructor with arg as 'Throwable cause'

查看:244
本文介绍了在java中为什么自定义异常也应该有一个构造函数,其中arg为“Throwable cause”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么在定义自定义异常时应该有下面的构造函数:

Can anyone please explain why we should have constructors like below when defining custom exceptions :

public MyException(Throwable cause) {
    super(cause);
}

public MyException(String message, Throwable cause) {
    super(message, cause);
}


推荐答案

它允许您添加到您的自定义异常实例信息有关抛出该异常的原因。

It allows you to add to your custom Exception instance information regarding the reason of throwing that exception.

当您捕获一个异常并抛出异常时,它很有用。

It is useful when you catch one exception and throw another.

例如:

try {
    ....
}
catch (SomeException ex) {
    throw new MyException ("some message", ex);
}

这篇关于在java中为什么自定义异常也应该有一个构造函数,其中arg为“Throwable cause”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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