What is the advantage of chained exceptions

Can anyone please provide information on the need for chained exceptions?

The article says it quite well:

Exception chaining allows you to map one exception type to another, so that a method can throw exceptions defined at the same abstraction level as the method itself, without discarding important debugging information.

That is, if you have a method that loads some object from a database, you may rather want some ResourceLoadException (closer related to the methods abstraction level) instead of a low-level SQLException even if that was the original source of the problem. However, if you simply catch the SQLException and throw a ResourceLoadException instead, you may loose important debugging information.

Thus, chaining the exceptions is a good alternative. You throw a “high-level” exception, well suited for the particular method, but chain it with the exception that caused it.

Else, the programmer can catch both the exceptions in the same code than having to throw a new Throwable instance?

I don’t quite follow your reasoning here. The point is that he should not need to worry about the SQLException at this level of abstraction.

Leave a Comment