What do you do when you’ve caught an exception?
Abort, Retry, Ignore
This article is a follow up to “Don’t Catch Exceptions“, which advocates that exceptions should (in general) be passed up to a “unit of work”, that is, a fairly coarse-grained activity which can reasonably be failed, retried or ignored. A unit of work could be:
- an entire program, for a command-line script,
- a single web request in a web application,
- the delivery of an e-mail message
- the handling of a single input record in a batch loading application,
- rendering a single frame in a media player or a video game, or
- an event handler in a GUI program
The code around the unit of work may look something like
[01] try { [02] DoUnitOfWork() [03] } catch(Exception e) { [04] ... examine exception and decide what to do ... [05] }
For the most part, the code inside DoUnitOfWork() and the functions it calls tries to throw exceptions upward rather than catch them.
To handle errors correctly, you need to answer a few questions, such as
- Was this error caused by a corrupted application state?
- Did this error cause the application state to be corrupted?
- Was this error caused by invalid input?
- What do we tell the user, the developers and the system administrator?
- Could this operation succeed if it was retried?
- Is there something else we could do?
Although it’s good to depend on existing exception hierarchies (at least you won’t introduce new problems), the way that exceptions are defined and thrown inside the work unit should help the code on line [04] make a decision about what to do — such practices are the subject of a future article, which subscribers to our RSS feed will be the first to read.
Paul Houle on August 27th 2008 in Dot Net, Exceptions, Java, PHP, SQL