What is the benefit of declaring the possible exception-throws from a C++ function? In other words, what does adding the keyword throw()
actually do?
I've read that a function declaration such as void do_something() throw();
should guarantee that no exceptions originate from the do_something()
function; however, this doesn't seem to hold true of functions called within do_something()
, thus making it a weak guarantee.
Please outline the usefulness (and best-use cases) of this language feature.
No one explains this better than Sutter
http://www.ddj.com/architect/184401544
The short version is
The C++ standard requires that the unexpected()
function is called if a function attempts to throw an exception that is not on its exception list. A short description of this from MSDN is here: http://msdn.microsoft.com/en-us/library/awbt5tew(VS.80).aspx
Most compilers do not actually support this C++ feature.
void do_something() throw();
This is a guarantee from the implementer's side that the function will never throw an exception. That is what a client of the function can expect. However, it also means any exception generated somewhere inside the function is handled and not rethrown back to the parent of do_something()
. Shame on he who re-throw
-eth from within, for there is nothing that'll stop him from throwing. This is because, throwing from within a function with an empty exception-specification is equivalent to throwing an exception not mentioned in the specification and making the std::unexpected()
is to be expected followed by program termination.
BTW: The generally accepted definition of strong exception guarantee is: If a public operation fails for some reason, an exception is thrown, and the object's state is left unchanged (atomic operation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With