名稱空間
變體
操作

std::set_terminate

來自 cppreference.com
< cpp‎ | 錯誤
定義於標頭檔案 <exception>
(C++11 前)
std::terminate_handler set_terminate( std::terminate_handler f ) noexcept;
(C++11 起)

f 設定為新的全域性 terminate 處理函式,並返回先前安裝的 std::terminate_handlerf 必須終止程式執行而不能返回其呼叫者,否則行為未定義。

此函式是執行緒安全的。每次呼叫 std::set_terminate 都與(參見 std::memory_order)後續呼叫 std::set_terminatestd::get_terminate 進行同步。

(C++11 起)

目錄

[編輯] 引數

f - 型別為 std::terminate_handler 的函式指標,或空指標

[編輯] 返回值

先前安裝的 terminate 處理函式,如果未安裝則為空指標值。

[編輯] 示例

#include <cstdlib>
#include <exception>
#include <iostream>
 
int main()
{
    std::set_terminate([]()
    {
        std::cout << "Unhandled exception\n" << std::flush;
        std::abort();
    });
    throw 1;
}

可能的輸出

Unhandled exception
bash: line 7:  7743 Aborted                 (core dumped) ./a.out

終止處理程式也適用於已啟動的執行緒,因此它可以作為用 try/catch 塊封裝執行緒函式的替代方法。在以下示例中,由於異常未處理,將呼叫 std::terminate

#include <iostream>
#include <thread>
 
void run()
{
    throw std::runtime_error("Thread failure");
}
 
int main()
{
    try
    {
        std::thread t{run};
        t.join();
        return EXIT_SUCCESS;
    }
    catch (const std::exception& ex)
    {
        std::cerr << "Exception: " << ex.what() << '\n';
    }
    catch (...)
    {
        std::cerr << "Unknown exception caught\n";
    }
    return EXIT_FAILURE;
}

可能的輸出

terminate called after throwing an instance of 'std::runtime_error'
  what():  Thread failure
Aborted (core dumped)

引入終止處理程式後,可以分析從非主執行緒丟擲的異常,並優雅地執行退出。

#include <iostream>
#include <thread>
 
class foo
{
public:
    foo() { std::cerr << "foo::foo()\n"; }
    ~foo() { std::cerr << "foo::~foo()\n"; }
};
 
// Static object, expecting destructor on exit
foo f;
 
void run()
{
    throw std::runtime_error("Thread failure");
}
 
int main()
{
    std::set_terminate([]()
    {
        try
        {
            std::exception_ptr eptr{std::current_exception()};
            if (eptr)
            {
                std::rethrow_exception(eptr);
            }
            else
            {
                std::cerr << "Exiting without exception\n";
            }
        }
        catch (const std::exception& ex)
        {
            std::cerr << "Exception: " << ex.what() << '\n';
        }
        catch (...)
        {
            std::cerr << "Unknown exception caught\n";
        }
        std::exit(EXIT_FAILURE);
    });
 
    std::thread t{run};
    t.join();
}

輸出

foo::foo()
Exception: Thread failure
foo::~foo()

[編輯] 另請參見

異常處理失敗時呼叫的函式
(函式) [編輯]
獲取當前的 terminate_handler
(函式) [編輯]
std::terminate 呼叫的函式型別
(型別定義) [編輯]