Java: Chained Exceptions

Here's an example of exception chaining or wrapping:

public Person getPerson(long id) {
    try {
        return db.selectPerson(id);
    } catch (SQLException e) {
        throw new InternalServerErrorExceptionThe SQLException is given as cause
for the InternalServerErrorException
e); } }

The above example the SQLException is the cause for the InternalServerErrorException.

The InternalServerErrorException "wrapps" the SQLException.

This makes sure that the service level API doesn't throw database level exceptions. In other words, the exceptions thrown are on the right level of abstraction which makes the API easier to work with.

Stack Traces

Causes are shown in stack traces. A stack trace of chained exceptions looks like follows:

Exception in thread "main" example.BusinessLevelException: Business level error
        at example.BusinessLevelAPI.businessLevelMethod(
        at example.ExChainExample.main(
Caused by: example.ServiceException: Service level error
        at example.Service.serviceMethod(
        at example.BusinessLevelAPI.businessLevelMethod(
        ... 1 more
Caused by: example.DatabaseException: Database level error
        at example.Database.databaseMethod(
        at example.Service.serviceMethod(
        ... 2 more
Chained exceptions should not be confused with suppressed exceptions.


Be the first to comment!