The Right Approach to Exceptions

Martin Nowak dawg at dawgfoto.de
Sat Feb 18 13:54:34 PST 2012


>> You don't want to use specific exceptions because it couples unrelated
>> code.  The distinction of recoverable Exceptions and non-recoverable
>> Errors is good enough in most cases.
>
> Not true, especially in library code. If you try to open a file,
> FileNotFoundException should be recoverable, but DiskFailureException
> should not. You need to distinguish between them.
>
That's what I said. Exception and Error.

>> Typed exception being used for local error recovery is about the same
>> as using error codes but at a bigger expense. On the plus side
>> exception can carry more specific error messages, which could be
>> solved for error codes too.
>
> The assumption is that exceptional conditions are, well, exceptional, so
> it shouldn't matter if you require extra CPU/memory to handle them.
>
> The worst thing is if we enforce generic exceptions instead of specific
> exceptions, and then code that *needs* to distinguish between different
> types of errors must pattern-match the error message to tell which one
> it is. That is unmaintainable, full of opportunities for bugs and i18n
> problems, and is absolutely NOT the way we want to go.
>
If you can recover from errors you know beforehand what kind of errors
may occur. That remove may fail if you haven't checked the path is clear.
What I'm saying is that error returns are more flexible for interfaces that
have know error cases. You can then either directly handle them or you may
translate them to exceptions using enforce. Always using exceptions forces
a certain programming model on you.

uint toUint(int value)
{
     if (value < 0) throw new ConvUnderflowException("Negative Value");
     return cast(uint)value;
}

void main(string[] args)
{
     int ival = parse!int(args[1]);
     uint uval;
     try
     {
         uval = toUint(ival);
     }
     catch (ConvUnderflowException)
     {
         uval = 0;
     }
}


More information about the Digitalmars-d mailing list