DIP33: A standard exception hierarchy
Lars T. Kyllingstad
public at kyllingen.net
Tue Apr 2 08:56:07 PDT 2013
On Monday, 1 April 2013 at 22:26:39 UTC, Jonathan M Davis 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. [...]
>
> 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.
Well, personally, I don't think this is much better than a switch
statement.
> 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.
Then you'd have two points of maintenance when you wish to add or
remove an error category.
> 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.
catch is *one* mechanism, switch is another. I propose to use
catch for coarse-level handling (plus the cases where exceptions
carry extra data), and switch for fine-level handling.
In my experience, most of the time, you don't even bother
distinguishing between the finer categories. If you can't open a
file, well, that's that. Tell the user why and ask them to try
another file. (I realise that this is highly arguable, of
course.)
Lars
More information about the Digitalmars-d
mailing list