The Right Approach to Exceptions

deadalnix deadalnix at gmail.com
Sun Feb 19 03:40:29 PST 2012


Le 19/02/2012 06:09, Jim Hewes a écrit :
> On 2/18/2012 5:59 PM, Robert Jacques wrote:
>> But you _always_ know what went wrong: An unexpected error occurred
>> while trying to do X, where X is whatever is inside the try-catch block.
>> Exceptions are for exceptional situations...
>
> Not to jump on you in particular for using the phrase "exceptions are
> for exceptional situations”, but I've always heard people say this in
> arguments about exceptions vs. returning error codes. Unfortunately
> those people usually never go on to define what exceptional situations
> are, so those trying to learn about using exceptions are left no better
> off. If exceptional cases are like divide-by-zero or hardware failures,
> then surely a bad parameter to a function is not “exceptional”. Then
> what? Is out-of-memory exceptional or something you should expect might
> happen given that memory is finite?
>
> I think of exception handling as tied to contract programming. A
> function has a specific job that it's supposed to do. If for any reason
> it cannot do that job successfully, an exception should be thrown. That
> can include even bad parameters (although if you have bad parameters to
> internal functions I'd think that is a design bug and could be handled
> by asserts). Look at the .NET library; it seems to work this way. So I
> think the term 'exceptional situations' has been kind of useless.
>

Well, I think you are messing up between contract and exception. Wrong 
parameters is a contract problem, not an exceptionnal situation.

The exemple you cited below is way more suited for an exception : 
someone unplug the USB device, then I trhow an Exception and it will 
cross all layers of my code to reach a point where it is recoverable.

Except that contract detail, your post make perfect sense.


More information about the Digitalmars-d mailing list