Alex Rivera | Logout

What is the advantage of chained exceptions

Asked 2011-02-16T19:03:48.577
14

I do not understand the advantages of having a chained exception in the code.

Considering the ResourceLoader example from java world, if the programmer knows of a possibility of encountering ResourceLoadException , why not catch the same exception instead of SQLException? Else, the programmer can catch both the exceptions in the same code than having to throw a new Throwable instance?

Edit
Report

2 Answers

2

I think the reason from that sample is that the author wishes to create a uniform interface which isn't dependent on some specific underlying system, like SQL. Hence, he converts the exception to the more general form, leaving the actual implementation transparent to the business logic.

However, in some cases it might be desirable to propagate an error like SQLException. This will be useful in places where one needs to take different actions based on the thrown Exception.

answered 2011-02-16T19:07:29.997
2

The first benefit is encapsulation. ResourceLoader might be an interface with several implementations (for instance one loading the resources from the database, while another loads them from the file system), where the implementation to use is selected at runtime. Then the caller should be agnostic to the root cause of why loading the resource failed, but might still wish to react to resource load failures. This is particularly useful if the interface declares two different exceptions to be thrown to which the caller might wish to respond differently (for instance, a TransientResourceLoadFailureException, where a retry might suceed, and a PermanentResourceLoadFailureException, where a retry is known not to succeed).

The second benefit of exception chaining is that each exception in the chain may have a different message, which allows to include additional information for debugging. In your case, note that the ResourceLoadException's message contains the name of the resource that could not be loaded, which is not guaranteed to be included in the SQLException, but might be necessary to reproduce the problem (certain databases are not exactly known for specific error messages).

These benefits come at the cost of having to write and maintain the catch blocks. You should decide on a case by case basis whether the benefits justify the cost.

answered 2011-02-16T19:49:43.473

Your Answer