函式
<exception>

std::set_terminate

terminate_handler set_terminate (terminate_handler f) throw();
terminate_handler set_terminate (terminate_handler f) noexcept;
設定終止處理函式
設定 f 作為終止處理函式

終止處理函式是在異常處理過程因某種原因不得不中止時自動呼叫的函式。當一個被丟擲的異常找不到匹配的 catch 語句時,或者因為其他使得異常處理過程無法繼續的異常情況發生時,就會發生這種情況。

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

程式可以透過呼叫 terminate 來顯式呼叫當前的終止處理函式

引數

f
不接受任何引數且不返回任何值的函式(void)。
該函式應終止程式的執行,而不返回給呼叫者。
terminate_handler 是一個不接受任何引數且不返回任何值的函式指標型別void.

返回值

先前的終止處理函式(如果有)。這可能是一個空指標
terminate_handler 是一個不接受任何引數且不返回任何值的函式指標型別。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// set_terminate example
#include <iostream>       // std::cerr
#include <exception>      // std::set_terminate
#include <cstdlib>        // std::abort

void myterminate () {
  std::cerr << "terminate handler called\n";
  abort();  // forces abnormal termination
}

int main (void) {
  std::set_terminate (myterminate);
  throw 0;  // unhandled exception: calls terminate handler
  return 0;
}

可能的輸出

terminate handler called
Aborted


資料競爭

呼叫此函式不會引入資料競爭,並且此類呼叫與後續對 set_terminateget_terminate 的呼叫同步。

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

異常安全

無異常保證:此函式(set_terminate)永遠不會丟擲異常。

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

另見