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

Jonathan M Davis jmdavisprog at gmail.com
Sun Aug 1 15:52:49 PDT 2010


On Sunday 01 August 2010 07:36:27 Jason Spencer wrote:
> == Quote from Jonathan M Davis (jmdavisprog at gmail.com)'s article
> 
> > For logic errors, efficiency isn't really an issue, since they
> > shouldn't be happening. If they are, go fix your code and it won't
> > be an issue.
> 
> That gets less true as the cost of a try block goes up.  Even if logic
> errors never occur, the infrastructure to check for them costs you
> something.  Ever compared the performance of a program w/ and w/o
> trys?
> 
> So, would you advocate for exceptions as the sole error reporting
> mechanism?  Return values are just for valid result values and
> everything else is an exception?  Where do you personally draw the
> line?
> 
> Jason

It really depends on what you're doing. I do think that exceptions are the 
better way to go, but it tends to be dangerous to say things like "always" and 
"never." Generally, however, I would use return for valid results only and use 
exceptions for errors. However, if error cases become very likely, then 
exceptions do tend to become a poorer solution since you don't want to be 
throwing lots of exceptions. Also, there are cases where you can take an error 
and simply turn it into a default value (particularly for things like parsing 
and conversion functions) if that's acceptable.

Still, I think that it generally makes for better code when you assume that the 
returned data is correct and then let exceptions deal with the error cases - 
particularly when dealing with user input and file I/O. And in such cases, 
efficiency is not generally the greatest concern. If you had cases where efficency 
was a great concern, then it might be worth looking at whether exceptions were 
the best way to handle things, but in the general case, I believe that they are.

As to where exactly I draw the line, I'd really have to look at the code in 
question to make any kind of judgement call. However, I'm generally going to go 
with exceptions unless I have a good reason not to, and I've found such reasons 
to be fairly rare.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list