If a function declared with an exception-specification throws an exception of a type not included in the specification, the function unexpected()
is called. The behaviour behavior of this function can be overridden within a project, but by default causes an exception of std::bad_exception
to be thrown. Unless std::bad_exception
is listed in the exception-specification, the terminate()
function will be called, leading to implementation-defined termination of the program.
...
In this non-compliant code example, the second function claims to throw only exception1
, but it may also throw exception2
.
Code Block | ||||
---|---|---|---|---|
| ||||
class exception1 : public exception {}; class exception2 : public exception {}; void foo() { throw exception2; // ok...since foo() promises nothing wrt exceptions } void bar() throw (exception1) { foo(); // bad, since foo() can throw exception2 } |
...
A simple compliant solution is to catch any exceptions thrown by foo{}
Code Block | ||||
---|---|---|---|---|
| ||||
void bar() throw (exception1) { try { foo(); } catch (...) { // handle error, without re-throwing it } } |
...