Boost logo

Boost :

Subject: Re: [boost] std::map::find() wrapper
From: Rob Riggs (rob_at_[hidden])
Date: 2011-04-30 17:18:31

On 04/30/2011 06:55 AM, Olaf van der Spek wrote:
> exceptions are for exceptional cases

That oft-used bromide lacks any useful information about when the use of
exceptions is appropriate.

Exceptions should be used (thrown) when contracts are violated or
invariants cannot be maintained. The only time they should not be used
in these cases is when checking the invariants would impact performance
to such a degree that allowing undefined behavior may be preferable.
And in this case, do what map and vector do: provide a checked and
unchecked version.

A precondition for at() is that the key exists in the map. It is
perfectly legitimate for at() to throw an exception for violating its

And /it is perfectly legitimate to make use of this behavior in one's
code/. That is, there is nothing wrong with allowing an exception to be
thrown if you can afford the stack unwinding.

Two bits of code:

if (foo.good()) {


try {
} catch (not_good&) {}

Both are valid. And sometimes the latter is most appropriate.

Personally, I tend to be more averse to functions that return bare
pointers. Given the choice of a function that returns a bare pointer
which may be NULL or using at() & try/catch, I would probably choose
at() first.

Then I might try a solution with boost::optional. (I just would prefer
that optional::operator*() threw a logic_error for uninitialized values
rather than declare its behavior as "undefined".)


Boost list run by bdawes at, gregod at, cpdaniel at, john at