Contracts or Exceptions?

spir denis.spir at gmail.com
Wed Mar 30 05:09:13 PDT 2011


On 03/30/2011 05:32 AM, 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." :)
>
> 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.
>
> 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.

These are sensible and well expressed guidelines, thank you.
In other languages, I happened to use exceptions as a // channel for 
side-information (eg 'nomatch' for a matching func), but in D I realised how 
'exceptionnally' (!) costly throwing & catching exceptions is, so that I do not 
do it anymore. No idea though whether this exceptional cost is perticular to D.

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list