Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit to limiting throws allowed by a C++ function? [closed]

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.

like image 312
Rob Avatar asked Mar 04 '09 05:03

Rob


3 Answers

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
like image 164
JaredPar Avatar answered Oct 26 '22 23:10

JaredPar


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.

like image 33
Greg Hewgill Avatar answered Oct 27 '22 01:10

Greg Hewgill


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).

like image 27
dirkgently Avatar answered Oct 27 '22 01:10

dirkgently