On Mon, 01 Apr 2013 18:26:22 -0400, Jonathan M Davis <[email protected]> wrote:

On Monday, April 01, 2013 21:33:22 Lars T. Kyllingstad wrote:
My problem with subclasses is that they are a rather heavyweight
addition to an API. If they bring no substance (such as extra
data), I think they are best avoided.

Except that they're extremely valuable when you need to catch them. Being able
to do something like

try
{
 ...
}
catch(FileNotFoundException fnfe)
{
 //handling specific to missing files
}
catch(PermissionsDeniedException pde)
{
 //handling specific to lack of permissions
}
catch(FileExceptionfe
{
 //generic file handling error
}
catch(Exception e)
{
 //generic error handling
}

can be very valuable. In general, I'd strongly suggest having subclasses for
the various "Kind"s in addition to the kind field. That way, you have the
specific exception types if you want to have separate catch blocks for different error types, and you have the kind field if you just want to catch the base
exception.

If anything, exceptions are exactly the place where you want to have derived classes with next to nothing in them, precisely because it's the type that the
catch mechanism uses to distinguish them.

In general, this is not enough. Imagine having an exception type for each errno number. Someone may want that!

Note that there are two categories of code dealing with thrown exceptions:

1. whether to catch
2. what to do

Right now, we have the super-basic java/c++ model of matching the type for item 1. D could be much better than that:

catch(SystemException e) if(e.errno == EBADF)
{
   ...
}

For item 2, once you have the caught exception, you have mechanisms to deal with the various fields of the exception. So even without improvements to #1, you can rethrow the exception if it's not what you wanted. Just the code isn't cleaner:

catch(SystemException e)
{
   if(e.errno != EBADF)
      throw e;
}

-Steve

Reply via email to