littlenoodles
littlenoodles

Reputation: 465

does throw in a C++ function declaration preclude throwing other exceptions?

I inherited a C++ project with a function defined like so:

void myDoc::parseDoc(string& path) throw(docError);

The parseDoc function calls a library that throws libError, and the main function that calls parseDoc catches both docError and libError and logs them. parseDoc doesn't throw any exceptions itself, but I would've expected the libErrors from the library to still get caught by main. They don't - I just get a core dump with nothing useful on the stack.

I tried various changes to parseDoc. Some of them get libError passed up the chain. and some don't:

  1. catch libError and rethrow it - doesn't work
  2. catch libError and copy it to a docError and throw that - works
  3. specify throw(docError, libError) and not catch anything - works
  4. remove the throw() from the function definition and not catch anything - works

So my question is - does adding a throw(docError) to this function definition specifically prevent other exceptions from being passed up the stack to the caller? If so, why would anyone want to do that? And if not specifying that a function throws exceptions just works the way I always thought exceptions were supposed to work, what's the point of the throw(e) specification in the first place?

Upvotes: 0

Views: 587

Answers (1)

Sebastian Redl
Sebastian Redl

Reputation: 71899

Yes, a throw specification does not allow any exceptions except the specified to escape the function.

As for why anyone would want that, the idea is documentation, showing exactly which exceptions the function will throw.

However, in reality, the concept proved to be so useless that throw specifications were (or will be, not sure about the exact status) actually removed in a newer version of C++. So the correct action to take is number 4, removing the specification.

Upvotes: 5

Related Questions