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(BusinessLevelAPI.java:8)
        at example.ExChainExample.main(ExChainExample.java:8)
Caused by: example.ServiceException: Service level error
        at example.Service.serviceMethod(Service.java:8)
        at example.BusinessLevelAPI.businessLevelMethod(BusinessLevelAPI.java:6)
        ... 1 more
Caused by: example.DatabaseException: Database level error
        at example.Database.databaseMethod(Database.java:5)
        at example.Service.serviceMethod(Service.java:6)
        ... 2 more
Chained exceptions should not be confused with suppressed exceptions.

Comments