How should exceptions be dispatched so that error handling and diagnostics can be handled in a centralized, user-friendly manner?
For example:
- A DataHW class handles communication with some data acquisition hardware.
- The DataHW class may throw exceptions based on a number of possible errors: intermittent signal, no signal, CRC failure, driver error. Each type of error gets its own exception class.
- The DataHW class is called by a number of different pieces of code that do different types of acquisition and analysis.
The proper error handling strategy depends on the type of exception and the operation being attempted. (On intermittent signal, retry X times then tell the user; on a driver error, log an error and restart the driver; etc.) How should this error handling strategy be invoked?
- Coding error recovery into each exception class: This would result in exception classes that are rather large and contain high-level UI and system management code. This seems bad.
- Providing a separate
catchblock for each type of exception: Since the DataHW class is called from many different places, eachcatchblock would have to be duplicated at each call site. This seems bad. - Using a single
catchblock that calls someExceptionDispatchfunction with a giant RTTI-basedswitchstatement: RTTI andswitchusually indicates a failure to apply OO design, but this seems the least bad alternative.
Avoid duplicating the catch blocks at each call site by catching (…) and calling a shared handler function which rethrows and dispatches: