Never use throw-declaration in C++

Never equip your class functions with throw-declarations.

If for any reason an exception gets thrown (inside or below that member), which is not derived from one of your throw-declared exceptions, you'll get an undefined exception along with a nice coredump. And this is not that easy to trace back.

You can only do this, if you have a compiler which ignores them completely (as Microsoft Visual Studio) or refuses to compile if the throwed exceptions don't match.

As I don't know of any C++-compiler which does the latter well enough, I only can give you the hint:
Never use throw-declarations in C++ or you'll be cursed with untraceable coredumps/crashes far in the future.

Since this page is hit quite regulary with search engines directly, I'll provide some additional information for the real interested ones.

We had quite problems in our code with the debugging of very strange Linux and AIX coredumps and meaningless backtraces.

The cause of this were constructs like following:

int test1(int i) throw(Exception1)
    throw Exception2;
  return 0;

Problems occour, if Exception2 is not derived from Exception1. In such a case, most compilers not even give you a warning but compile correctly and generate an executable.
But when during execution Exception2 is thrown and not catched before leaving the method the exception is transformed into an unexpected_exception and not catchable anymore even with catch(...).
It's only catchable with the unexpected_exception-handler, but in that case you are not able to get the type/class of the exception, nor where it originated from.

A nice example can be found in Bruce Bruce Eckel's Thinking in C++, 2nd Ed: Cleaning up, but there he rethrows the exception in the unexpected-handler and it gets catched later in the next upmost method on the call-hirarcy.
Besides that this is in my eyes a very ugly workaround I don't think that this works on many platforms.


Similar entries