Re: why a member "swap" function shouldn't throw?
Andre Kostur wrote:
rpbg123@yahoo.com (Roland Pibinger) wrote in news:4672bdfb.9209182
@news.utanet.at:
On Fri, 15 Jun 2007 05:21:10 -0700, Jess wrote:
It is said that if I implement a "swap" member function, then it
should never throw any exception.
This may be a recommendation but it's not a fixed requirement. You can
use the exception specification throw() to guarantee that no exception
is thrown from a function.
Um. No. throw() says that you don't intend for exceptions to be
thrown/escape from that function... but in reality, should an exception end
up attempting to escape from that function, all that will do it convert
that exception into a std::bad_exception. So specifying throw() doesn't
guarantee that there will be no exceptions in that function.
You won't ever get any exception whose type is not listed in the throw
specifier.
If an exception is thrown that doesn't match the throw specifier, the
implementation calls unexpected(). The default behavior of unexpected()
is to call terminate().
Your application can replace the unexpected handler by calling
set_unexpected with the address of a suitable handler function. The
handler function isn't allowed to return. It can call terminate(), it
can throw another exception object, or it can rethrow the object that
was thrown. If it throws an exception whose type is one of the types
listed in the throw specifier, then unwinding continues. If it throws an
exception whose type is not listed in the throw specifier AND the list
of types in the throw specifier includes std::bad_exception, the thrown
exception object is replaced by an object of type std::bad_exception. If
the list of types in the throw specifier does not include
std::bad_exception, the implementation calls terminate().
The details are in [except.unexpected]. They're summarized in the third
paragraph of that section:
Thus, an exception-specification guarantees that only
the listed exceptions will be thrown. If the
exception-specification includes the type std::bad_exception
then any exception not on the list may be replaced by
std::bad_exception within the function std::unexpected().
--
-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)