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.

Ali

Reply via email to