开发者

Is there inner exception concept in java

.Net's exception can contain inner exceptions? I want to know if Java has similar thing or 开发者_开发问答not?


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.)


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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜