函式
<exception>

std::set_unexpected

unexpected_handler set_unexpected (unexpected_handler f) throw();
unexpected_handler set_unexpected (unexpected_handler f) noexcept;
設定意外處理函式
f設定為意外處理函式

當一個函式丟擲一個不在其動態異常說明(即在其throw說明符)中的異常時,意外處理函式會被自動呼叫。

意外處理函式可以處理該異常,並且應以終止(呼叫terminate或其他方法,如exitabort)或丟擲異常(甚至重新丟擲相同的異常)來結束。如果丟擲(或重新丟擲)的異常不在函式的動態異常說明中,但丟擲的是bad_exception,則會丟擲bad_exception。否則,如果新的異常也不在動態異常說明中,則會自動呼叫terminate

在程式第一次呼叫此函式之前,預設行為是呼叫terminate

引數

f
不接受任何引數且不返回任何值的函式(void)。
該函式不應返回。它應該丟擲異常或終止。
unexpected_handler是一種函式指標型別,不接受任何引數並返回void

返回值

先前存在的意外處理函式(如果存在)。這可能是一個空指標
unexpected_handler是一種函式指標型別,不接受任何引數且不返回任何值。

相容性

*dynamic-exception-specifier*的使用已被棄用(自C++11起)。

示例

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;
}

輸出

unexpected called
caught int


資料競爭

呼叫此函式不得引發資料競爭,並且所有此類呼叫都與後續對set_unexpectedget_unexpected的呼叫同步。

請注意,此要求僅適用於set_unexpected函式,但不一定適用於作為引數(f)傳遞的意外處理函式

異常安全

無丟擲保證:此函式(set_unexpected)從不丟擲異常。

請注意,如果f是一個未實現適當功能(如上所述)的函式,或者f是一個無效指標或空指標,則會導致未定義行為

另見