On exceptions, errors, and contract violations

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Mon Oct 6 07:36:42 PDT 2014


On 10/3/14 1:40 PM, Sean Kelly wrote:

> Setting aside exceptions for the moment, one thing I've realized about
> errors is that in most cases, an API has no idea how important its
> proper function is to the application writer.

This is the thing I have been arguing. Inside a library, the idea of 
input to the function being user defined or program-defined is not 
clear. It means that any user-defined input has to be double checked in 
the same exact way, to avoid having an error thrown in the case that the 
library function throws an error on such input. The other side, any 
program-caused errors that end up triggering exceptions (a misnamed 
filename for opening a config file, for instance), needs to treat this 
exception as an error and halt the program with an appropriate stack trace.

What makes sense to me is:

1. If you send in an obvious programming error (i.e. null instead of an 
expected target address), throw an error. This can be done in contract 
precondition scopes. Such things could NOT be generated by user.
2. If you send in something that doesn't make sense, but could be 
user-generated, throw an exception. User-generated is a very fuzzy 
thing, but we should conservatively assume the input is user-generated.
3. If anything happens internally to the function, treat it as an error.

If an input causes an exception, but the input was program generated, 
don't catch it in the calling scope! Just let the runtime handle it as 
an error, and exit the program. Any uncaught exceptions should be 
treated as errors anyway.

It might be a good idea to have an umbrella exception type that means 
"input invalid." This gives some easy way to catch all such exceptions 
and print them properly in the case where it's user-defined input.

-Steve


More information about the Digitalmars-d mailing list