[Exceptional C++ Style] Fw: Item 11: Try and Catch Me

Ric Parkin ric.parkin at ntlworld.com
Wed Dec 1 07:10:04 EST 2004


From: Kevlin Henney <kevlin at curbralan.com>
> David Sykes <d.sykes at pindar.com> writes
> >
> >It seems to me, then, that the open routine cannot tell if the file is
> >essential or secondary, and so can't know whether to throw an exception or
> >not.
> >If, as has been suggested, there was an exception and non exception method
> >then the caller could choose. Having the constructor throw an exception and
> >open return fail value would fit the guidelines of exceptions being good for
> >constructors and return values emitted by operations that can.
> 
> It might also be considered an inconsistent and indecisive design, 
> trying to please all the people all of the time. Such accommodating 
> interfaces tend to bloat as well as annoy users with their vague 
> helpfulness :-) Choice is not of itself a virtue.


This cuts straight to the heart of why it's often difficult to write a good library - without knowing what is needed in practice, it's tempting to add everything in the theory that it might be useful.

A *good* library/class etc, IMO, should actively steer the client into using it in one good way, but not close off  building other ways.


As an example similar to the motivating file open case, I once wrote a simple COM pointer wrapper (doesn't everyone?). This has the usual program of what to do if a Query Interface failed - exception, or error code, or set pointer to null?

In this case I reasoned that as experience had shown:
- most time you used QI to get an expected interface
- but less often used it to to see if an optional interface was there
- the rest of code was going to be exception safe anyway

then the constructor that did the QI should throw an exception, unless an optional no_throw parameter was specified, which would set the pointer to NULL on failure.

But if the experience had shown something else, eg was going to be used in code that was *never* going to be exception safe, then a completely different solution may have been better.

In other words Context Matters - it drives the expected usage, which drives the design.

Ric


-----------------------------------------
Email provided by http://www.ntlhome.com/





More information about the Effective-cpp mailing list