std::
set_unexpected
函数 <exception>
C++98 |
unexpected_handler set_unexpected (unexpected_handler f) throw();
|
C++11 |
unexpected_handler set_unexpected (unexpected_handler f) noexcept; |
设置意外处理程序函数
设置f为意外处理程序函数。
意外处理函数是一个函数在抛出动态异常说明(即抛出说明符中)中没有的异常时自动调用的函数。
意外处理函数可以处理异常,并通过终止(调用terminate或其他方法,
如exit或abort)或抛出异常(甚至再次抛出相同的异常)来结束异常。
如果抛出(或重新抛出)的异常不在函数的动态异常说明中,而bad_exception在动态异常说明中,
则抛出bad_exception。否则,如果新异常也不在动态异常说明中,则会自动调用terminate函数。
在程序第一次调用此函数之前,默认行为是调用terminate函数。
☲ 参数
-
f
-
不带参数也不返回值的函数(void)。
函数不会返回。它要么抛出异常,要么终止。
unexpected是一个没有形参且返回void的函数指针类型。
☉ 返回值
前面的意外处理函数(如果有的话)。这可能是一个空指针。
unexpected是一个不接受参数也不返回值的函数指针类型。
⇄ 兼容性
不赞成使用动态异常说明符(自c++ 11以来)。
☣ 示例
// 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;
}
|
输出:
unexpected called
caught int
⇄ 数据竞争
调用这个函数不会引起数据竞争,并且任何这样的调用都会与后续的set_unexpected和get_unexpected调用同步。
注意,这个要求只适用于set_unexpected函数,而不一定适用于作为参数(f)传递的意外处理函数。
☂ 异常安全性
无抛出保证:该成员函数从不抛出异常。
注意,如果f是一个没有实现正确功能(如上所述)的函数,或者f是一个无效或空指针,它会导致未定义的行为。
🍄 另请参阅