Discussion
In brief, don't bother with exception specifications. Even experts don't bother. The main problems with exception specifications are that they're only "sort of" part of the type system, they don't do what most people think, and you almost always don't want what they actually do.Exception specifications aren't part of a function's type, except when they are. They form a shadow type system whereby writing an exception specification is variously:
- Illegal:
In a typedef for a pointer to function. - Allowed:
In the identical code without the typedef. - Required:
In the declaration of a virtual function that overrides a base class virtual function that has an exception specification. - Implicit and automatic:
In the declaration of the constructors, assignment operators, and destructors when they are implicitly generated by the compiler.
A common but nevertheless incorrect belief is that exception specifications statically guarantee that functions will throw only listed exceptions (possibly none), and enable compiler optimizations based on that knowledge.Item 9).These is no easy fix for the problems described in this Item. In particular, the problems are not easily solved by switching to static checking. People often suggest switching from dynamically checked exception specifications to statically checked ones, as provided in Java and other languages. In short, that just trades one set of problems for another; users of languages with statically checked exception specifications seem to equally often suggest switching to dynamically checked ones.