java java中是否有内部异常概念
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5244858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there inner exception concept in java
提问by user496949
.Net's exception can contain inner exceptions? I want to know if Java has similar thing or not?
.Net 的异常可以包含内部异常吗?我想知道Java是否有类似的东西?
回答by Jon Skeet
Absolutely - you can retrieve the inner exception (the "cause") using Throwable.getCause()
. To create an exception with a cause, simply pass it into the constructor. (Most exceptions have a constructor accepting a cause, where it makes sense.)
绝对 - 您可以使用Throwable.getCause()
. 要创建带有原因的异常,只需将其传递给构造函数即可。(大多数异常都有一个接受原因的构造函数,这是有意义的。)
回答by Dónal
You can set the inner exception (AKA the cause) in two ways. If you're instantiating the exception yourself, pass the inner exception to the (outer) exception's constructor, e.g.
您可以通过两种方式设置内部异常(也称为原因)。如果您自己实例化异常,请将内部异常传递给(外部)异常的构造函数,例如
try {
// some code that throws innerException
} catch (Exception innerException) {
throw new OuterException(innerException);
}
On the other hand, if the outer exception does not have a constructor that allows you to set the inner exception, or you don't instantiate the outer exception yourself, you can set it using
另一方面,如果外部异常没有允许您设置内部异常的构造函数,或者您没有自己实例化外部异常,则可以使用
outerException.initCause(innerException);
回答by Michael Borgwardt
Since Java 1.4, java.lang.Throwable
has constructors that take another Throwable
as parameter, and a getCause()
method that returns it. Pretty much all exceptions in the standard API and most of those implemented in other libraries make use of this facility.
从 Java 1.4 开始,java.lang.Throwable
具有将另一个Throwable
作为参数的构造函数,以及一个getCause()
返回它的方法。标准 API 中的几乎所有异常以及在其他库中实现的大多数异常都使用此功能。
回答by JB Nizet
All the exceptions can be chained in Java. This means that you may throw an exception and provide another exception (Throwable in fact) as the cause of the exception you're throwing. Look at the javadoc for Exception.
所有异常都可以在 Java 中链接起来。这意味着您可能会抛出异常并提供另一个异常(实际上是 Throwable)作为您抛出异常的原因。查看Exception的javadoc。