Categories
patterns

Pattern Patter: Absorbing Exceptions

Context

  • Exceptions are rare
  • There is no language support for exceptions

Forces

Indications

Code that looks like this:

status = add_primitive (data_structure, value1);
if (status != success) return status;

status = add_routine (data_structure, value2);
if (status != success) return status;

Pattern

Many times you are accumulating information into a data structure. For some errors, you don’t really want to check all the time. There are several reasons for this:

  • It takes time to check the status everywhere, but exceptional situations are infrequent.
  • It’s easy to forget to check.

Another symptom – mixing concerns at two levels. We would like to ignore the things that go wrong at lower levels. (For example, space overflows in a data structure are not at the same level of concern as semantic errors in the values being inserted there.)

So, make the data structure absorb exceptions. After the first exception, the data structure is “dead” as far as new activity. It still accepts calls to add items, but these have no effect on the contents. The data structure should provide a means of testing its status.

In this way, a series of operations can be performed, and then their success tested at the end of the sequence.

Related Ideas

This is related to Ward Cunningham’s CHECKS pattern (PLOP’94).