Boost logo

Boost :

From: Emil Dotchevski (emildotchevski_at_[hidden])
Date: 2006-08-28 19:22:16


Beman Dawes wrote:
> For a library function:
>
> Some system errors are best handled by aways throwing an exception.
> For example, a constructor should always throw if there is no way to
> leave
> the object in a valid state when a system error is encountered.
>
> Some system errors are best handled by ignoring the error. For
> example,
> an error in a destructor.

I think that it is the responsibility of the user to make sure destructors
they write don't leak exceptions, and in general to implement the
error-handling, given the specifications of the library.

It is the responsibility of the library implementer to decide whether a
specific function should throw to indicate a failure, or whether returning
an error code is more appropriate. Otherwise, we shift the responsibility
for this decision on the user, and typically they are no experts in the
problem domain of the library.

> But for all the other cases, the recommended approach is to provide
> throwing and non-throwing versions of the function, and let the user
> choose which is best for a given use:
>
> whatever foo(); // always throws on error
> whatever foo( error_code & ec ); // never throws on error

I, as a user of the library which gives me this option, would be
disappointed if I have to use such an interface. Note that even if the
library always throws under certain condition, I can easily write code to
prevent such exceptions from propagating in contexts where they would cause
problems, such as in destructors or at a DLL boundary.

> Although this works well, it has the unfortunate consequence of
> doubling
> the number of functions. That makes the interface harder to understand
> and is a pain to implement, document, and maintain.

Indeed.

> A refinement is for the <error_code.hpp> header to provide a dummy
> error_code that is interpreted as a request to thrown on errors:
>
> extern error_code throw_on_error;
>
> Then only a single signature is required:
>
> whatever foo( error_code & ec = throw_on_error );
>
> On an error, the implementation of foo throws if ec !=
> &throw_on_error, otherwise it sets ec to the appropriate error_code
> and returns without throwing.

What if the user wants some failures in foo() to be reported as errors, and
others to be reported by throwing an exception? There are contexts in which
this is *exactly* what the user may want. I don't think that it is any less
reasonable to support this than to support the option for users to decide
whether they want exceptions from a given function in the first place.

--Emil Dotchevski


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk