简体   繁体   中英

How to write Chained Exception Java classes

Specifically, which constructors should be overridden to qualify an exception as chainable ?

Throwable(Throwable cause) , Throwable(String message, Throwable cause) , or both?

Resources:

http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html https://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html


The following example shows how to use a chained exception.:

try {

} catch (IOException e) {
    throw new SampleException("Other IOException", e);
}

Unclear what you mean by "chainable" here.

Given the links that you gave however, I'll assume that you mean that a Throwable has another Throwable as a cause.

In this case you have no choice but to use the appropriate constructor; for instance:

public class Root
    extends Exception
{
    public Root(final String msg, final Throwable cause)
    {
        super(msg, cause);
    }
}

Another, less known solution, but which exists since Java 7, is to "suppress" the exception. See this link .

Which means that you should first define what you mean by "chained exceptions". An exception, by its nature, is pretty much "final"; the need to embed exceptions into other exceptions is rare, but not unheard of (as to suppressed exceptions, see here for an example)

So, define your use case first and foremost!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM