views:

683

answers:

4

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.

A: 

Basically, by declaring the function with throw(); you tell the compiler that you are one hundred per cent certain that the function is not going to throw any exceptions, allowing the compiler to perform some optimizations. If your function throws an exception anyway, you're in trouble, since it most likely results in undefined behavior.

arul
Well-defined behavior, actually: it calls unexpected(). Poorly implemented behavior, yes, but well-defined.
MSalters
+2  A: 

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.

Greg Hewgill
>> Most compilers do not actually support this C++ feature << - and for an example, see the MSVC documentation page you pointed to...
Michael Burr
+1  A: 
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).

dirkgently
+12  A: 

No one explains this better than Sutter

http://www.ddj.com/architect/184401544

The short version is

  1. Never write an exception specification
  2. Except possibly an empty one
JaredPar