The Right Approach to Exceptions
H. S. Teoh
hsteoh at quickfur.ath.cx
Sun Feb 19 00:49:50 PST 2012
On Sun, Feb 19, 2012 at 02:04:50AM -0600, Andrei Alexandrescu wrote:
> On 2/19/12 12:56 AM, Jonathan M Davis wrote:
> >I think that being able to have a catch block which took multiple
> >exception types would be plenty. There are times when it would be
> >very valuable to be able to use the same catch block for multiple
> >exceptions without having to catch their base type (which would then
> >potentially catch other exceptions which you didn't want to catch).
> >So, something like that second catch block that you have there would
> >be very valuable.
> So now hierarchies are not good?
It's not a simple black-or-white decision we're dealing with here. :)
Although exception hierarchies are currently the best we have, it's not
perfect, and it does have its own flaws. If we can figure out a better
system that fixes those flaws without compromising the good points of
using a class hierarchy, that would be even better.
The core of the problem is this: when an exception happens, it's within
a specific context with the associated domain-specific data. This
context and domain-specific data can be totally disparate types.
For example, a FileNotFound exception occurs in the filesystem, and is
associated with a filename. A SeekError also occurs in the filesystem,
is associated with a file (not necessarily equivalent to a filename),
and a seek offset. By contrast, a NetworkTimeout error happens in the
network stack, is associated with a particular protocol (say TCP), a
particular network socket (with its own associated IP address, etc.),
and a particular timeout value. It has no associated filename, or seek
So you have a bunch of exceptions, each of which is associated with a
bunch of info that, in general, have no relation with any info
associated with another exception. The problem at hand is: how do you
represent this info in a useful way? Generally speaking, the only common
thing between all exceptions is the fact that they are, well,
exceptions. And some of them are more closely related to each other than
others -- file-related exceptions may, for example, share the fact that
they are tied to a specific file.
To me, this is a giant hint that OOP is a good solution. You want a
class hierarchy rooted at Exception. And groups of related exceptions
probably should be rooted under their respective base classes under
If you have a better way to solve this, I'm waiting to hear it.
Gone Chopin. Bach in a minuet.
More information about the Digitalmars-d