function
<exception>
std::set_unexpected
unexpected_handler set_unexpected (unexpected_handler f) throw();
unexpected_handler set_unexpected (unexpected_handler f) noexcept;
Set unexpected handler function
Sets f as the unexpected handler function.
The unexpected handler function is a function automatically called when a function throws an exception that is not in its dynamic-exception-specification (i.e., in its throw
specifier).
The unexpected handler function can handle the exception and shall end either by teminating (calling terminate or some other method, such as exit or abort) or by throwing an exception (even rethrowing the same exception again). If the exception thrown (or rethrown) is not in the function's dynamic-exception-specification but bad_exception is, a bad_exception is thrown. Otherwise, if the new exception is not in the dynamic-exception-specification either, terminate is automatically called.
Before this function is called by the program for the first time, the default behavior is to call terminate.
Parameters
- f
- Function that takes no parameters and returns no value (
void
).
The function shall not return. It shall either throw an exception or terminate.
unexpected_handler is a function pointer type taking no parameters and returning void
.
Return value
The previous unexpected handler function, if any. This may be a null-pointer.
unexpected_handler is a function pointer type taking no parameters and returning no value.
Compatibility
The use of dynamic-exception-specifiers is deprecated (since C++11).
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
// set_unexpected example
#include <iostream> // std::cerr
#include <exception> // std::set_unexpected
void myunexpected () {
std::cerr << "unexpected called\n";
throw 0; // throws int (in exception-specification)
}
void myfunction () throw (int) {
throw 'x'; // throws char (not in exception-specification)
}
int main (void) {
std::set_unexpected (myunexpected);
try {
myfunction();
}
catch (int) { std::cerr << "caught int\n"; }
catch (...) { std::cerr << "caught some other exception type\n"; }
return 0;
}
| |
Output:
unexpected called
caught int
|
Data races
Calling this function shall not incur a data race, and any such calls are synchronized with subsequent calls to set_unexpected and get_unexpected.
Notice that this requirement applies only to the set_unexpected function, but not necessarily to the unexpected handler function passed as argument (f).
Exception safety
No-throw guarantee: this function (set_unexpected) never throws exceptions.
Notice that if f is a function that does not implement the proper functionality (described above), or if f is an invalid or null pointer, it causes undefined behavior.