- Exception Handling Strategies
- Exception Handling Strategy - Overview
- Exception Handling Requirements
- Application Survival
- Notifying Relevant Parties
- Error Diagnostics and Reproduction
- Separation of Abstraction Layers
- More Readable and Maintainable Code
- Error Location and Context
- Error Causes, Types and Reactions
- Strategy Elements
- Error Detection
- Error Information Gathering
- Throwing Exceptions
- Propagating Exceptions
- Catching Exceptions
- An Exception Handling Strategy Template
- An Exception Class Template
- Throwing the AppException
- Propagating the AppException
- The ErrorInfo List
- Catching the AppException
- Avoid Exception Hierarchies
Separation of Abstraction Layers
When you search the internet for advice on exception handling you will often see people say things like:
The upper layers in an application stack should not know anything about the lower layers. Hence they should not know how to handle special exceptions thrown from these layers.
What does this mean?
Imagine you are developing a persistence layer in your application and you decide to hide it behind a DAO layer. In other words, you don't want the layers of your application using the DAO layer to know what technology you have chosen underneath. Therefore, you don't want the layers above to know about any exceptions thrown from the DAO layer that are specific to the underlying persistence technology.
For instance, in JDBC, Java's database abstraction API, several of the methods may throw an SQLException. If your DAO's methods throw an SQLException, it reveals the underlying persistence technology, JDBC. If you were to change to an object oriented database or an XML file your DAO layer might all of a sudden throw exceptions related to these API's instead. This would break your code.
Instead, convert the exception thrown by the underlying persistence technology to a
DAOException or an
AppException. That way you can change the underlying persistence technology, without having to change
the exceptions declared thrown in the DAO methods.
Separation of abstraction layers is a secondary goal of an effective exception handling strategy in my opinion. It is definitely nice to have, but you can write an effective exception handling strategy, even if this goal isn't entirely met.