In Monday’s post, “Out-of-Band Error Reporting Without Exceptions”, I described a method for elegantly obtaining three out of five major advantages of C++ exceptions without actually using them. Now I’ll tell you how to go about grabbing a fourth advantage: exception type hierarchies.
C++ exceptions are hierarchical, and their hierarchy is a type hierarchy such that a more-derived exception can be treated, if desired, as one of its base exception types. For example, a FileNotFoundException
might be derived from FileIOException
. Some code may choose to handle FileNotFoundException
s distinctly from other FileIOException
s. Other code might delegate all FileIOException
s to a common handler. In C++ this is done with implicit typecasting in the catch
statements in a try
block.
Wouldn’t it be useful if we could do something similar with the ErrorReport
and CheckedValue
classes that were defined in Monday’s post, instead of just having an error/not-an-error indicator and a human-readable message? Well, we can. It’s easy to use but a little tricky to set up.