The Right Approach to Exceptions

Jim Hewes jimhewes at gmail.com
Sun Feb 19 11:00:52 PST 2012


On 2/19/2012 3:40 AM, deadalnix wrote:
> Le 19/02/2012 06:09, Jim Hewes a écrit :
>
> 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.

Then what do you do when bad parameters are passed? Do you return error 
codes using the function return mechanism? Do you use error codes for 
some errors and exceptions for others? Why? What's the strictly defined 
criteria for “exceptional” so that anyone can apply it to their own 
development and know when to use one or the other? If you use return 
codes for bad parameters, then does the caller always need to write 
error handling code to check for the bad parameter error?

I did point out that internal and external bad parameters are a 
different case. If you're talking about an exposed API for others to 
use, and it's something like a C interface from a DLL where you don't 
want to propagate exceptions, then of course you would return an error 
code or something similar. But if you're writing a function that you're 
going to call with your own code, then I'd say asserts can be used. And 
if it's a library that's meant to be called by others from the outside, 
but by the same language, then I say you can use exceptions. Examples 
are the argument exceptions in the C++ Std Lib and the .NET Framework.

I think the fact that these things are called exceptions, and that 
people then derive the word "exceptional" from that is misleading. But I 
know these types of things are always debated as religion and I suppose 
they will be for a while. :)

Jim


P.S. Sorry, I tend to use 'parameter' and 'argument' interchangeably and 
probably should not.


More information about the Digitalmars-d mailing list