yegeniy
yegeniy

Reputation: 1292

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

Upvotes: 0

Views: 145

Answers (1)

fge
fge

Reputation: 121702

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!

Upvotes: 1

Related Questions