Navigation:  Programming Cookbook > Exception Handling >

Exception Hierarchies

Previous pageReturn to chapter overviewNext page

An advantage of the class based exception mechanism used in Dolphin, is that hierarchies of exceptions can be defined, and the more specialised exceptions can be caught and handled by handlers written for their superclasses, allowing one to exploit the polymorphic behaviour of the specific instances from a generic handler. However, deeply nested hierarchies of increasingly specialised exceptions may well prove overly complex, and be more trouble than they are worth. Subtle distinctions may not be that useful in the handlers since one generally wants to minimise the amount of error handling code, and catch and handle the most generic level of error that permits recovery without suppressing unexpected errors.

The most important consideration when adding new exception classes is that they should be sufficiently specific to enable identification and handling of the error at the correct level. A good rule of thumb is to introduce one generic error class, and quite specific subclasses of that as the need arises. An example of this can be seen in the base system in the Win32Error hierarchy. Win32Error is raised when some error calling an operating system function is encountered, but there are also very specific subclasses such as OutOfMemoryError and GPFault to handle specific host system errors. Specific error instances can be raised off the more generic class when appropriate (using the Factory pattern), and this does make it easier to add new specific exceptions.

If one can identify situations where one does wish to group the handling of specific exceptions, then there may be a case for introducing another level in the hierarchy. However it is worth remembering that exceptions need not necessarily be related by hierarchy to be caught and handled by the same handler, since there is a mechanism for catching specified sets of exceptions (and one can quite easily add one's own mechanisms for determining catchers too). Furthermore because Smalltalk does not rely on inheritance relationships for polymorphic behaviour, as long as all the handled exceptions support the necessary protocol, then there is no requirement for them to share any common ancestor except Exception itself.