Casting an expression to bool means testing for 0 or !=0 for arithmetic types

Jason Spencer spencer8 at sbcglobal.net
Sat Jul 31 20:15:58 PDT 2010


== Quote from Dmitry Olshansky (dmitry.olsh at gmail.com)'s article
> Honestly, I'd suggest using exceptions instead of error codes.

This seems to be an increasingly common but still expensive suggestion
for error handling.  Unless D has made great strides in exception
performance (which is entirely possible), I still believe that, where
performance is anything like an issue anyway, exceptions should be
used only for truly exceptional condition--not alternate flow that
could/should be expected.

But I'm not just being a curmudgeon; I also have a suggestion.  If you
really want to take different paths based on a function return, make
that return an object.  This is what exceptions do, but it need not be
so expensive.  You could have a generic return class that has a
string, a value, and casts to bool to give you most of what exceptions
and bool return types give.  But you can also sub-class that class and
add polymorphic behavior to avoid the switch on value.  Or make it a
singleton and not pass it back.  Or have one for each important call
path, to which every called function can add delegates to run
onError() or run deferred at some root level.

Some of this would be a lot of work to setup, but I find it pretty
generic.  I should probably make a library and post it.  For the stuff
that most folks use exceptions for (i.e. to hold a string,) this class
is easy to write, and costs must less at run-time.

I will freely allow the critique that if do you this, then you'd have
to check the return object after each call to see if there's error
handling required.  But I see this as a chief benefit for the
maintainer (usually me in 6 months after I've forgotten everything
about the code.)  It spells out that there is another code path that's
important to consider when changing things.  Letting exceptions go by
tends to obfuscate that.  For out of memory, sure throw and don't
catch.  But for input string didn't parse, you want to handle that
safely, informatively, gracefully, or whatever your robustness
requirements are.  So make it clear to someone that it needs to be
handled.

I see a lot of exception-unsafe code.  I think programmers often don't
appreciate that your function may suddenly return between any two
arbitrary function calls, and almost between any two arbitrary
statements.  You have to really design carefully for exceptions.  So
it turns out this problem is a tough one and requires effort no matter
what.

Just a thought.
Jason


More information about the Digitalmars-d-learn mailing list