Contracts or Exceptions?

Kai Meyer kai at unixlords.com
Wed Mar 30 08:42:17 PDT 2011


On 03/29/2011 09:32 PM, Ali Çehreli wrote:
> On 03/29/2011 03:40 PM, Kai Meyer wrote:
>
>  > I was given two words of advice on exceptions:
>  > "Use exceptions for the exceptional"
>  > "Use exceptions only for the exceptional"
>
> Those advices are given by wise people: they are wise only because they
> leave the definition as vague as "exceptional." :)
>

Ya, now that I'm thinking about it a little more, we were talking about 
what sort of things you can do to increase performance. This was 
actually pretty far down the list, after considering things like 
profiling, improving algorithms, using built-in types instead of 
classes, ect. Exceptions are a little more expensive than condition 
statements.

> And what do we do for the "not so exceptional"? Do we return error
> codes? So the function implementation will be complicated and the caller
> code will be complicated.

You're right. I would consider those complications only if the 
optimisation I'm after justifies them. For example, if our profiler 
indicates that the function is running slowly due to handling a lot of 
exceptions (which probably won't be the first thing the profiler finds 
is running slow), we could use conditional statements to speed things up 
a bit.

if (good data)
   do work
else
   report "can't do work"

Would be faster than:

try
   do work
catch
   report "can't do work"

I'll also add that the same person who gave me this advice also likes to 
say "Premature optimisation is the root of all evil."

>
> Exceptions are a great tool to eliminate the need for error codes.
>
> Here is what I follow:
>
> - Functions have specific tasks to do; if those tasks cannot be
> accomplished, the function must throw.
>
> In some cases the function can continue, but that behavior must be
> documented. For example, if an HTML library function is responsible for
> making HTML headers, of which only the levels in the range of 1-6 are
> valid, that function may throw when the level is outside of the valid
> range, for in that case it cannot "make an HTML header"; or it can
> document that if the level is outside of the range, 1 or 6 will be used.
>
> - Catch exceptions only when there is a sensible thing to do at that
> level: log an error, skip that operation, go back to the user with an
> error code, take corrective action, etc.
>
> Disclaimer: That is what I follow in C++ code. I don't have experience
> with exception safety in D. I don't know issues that may be specific to D.
>
> Ali
>


Thanks for your insight Ali :) I'm not sure D's exceptions are much 
different than C++'s. I think you're right on.


More information about the Digitalmars-d-learn mailing list