std::uncaught_exception, std::uncaught_exceptions

從 cppreference.com
< cpp‎ | error
在標頭 <exception> 定義
(1)
bool uncaught_exception() throw();
(C++11 前)
bool uncaught_exception() noexcept;
(C++11 起)
(C++17 棄用)
(C++20 移除)
int uncaught_exceptions() noexcept;
(2) (C++17 起)
(C++26 起為 constexpr)
1) 檢測當前線程是否有生存的異常對象,即被拋出或重拋出且未進入匹配的 catch 子句、std::terminatestd::unexpected 的異常。換言之,std::uncaught_exception 檢測當前是否在進行棧回溯
2) 檢測當前線程已經拋出或重拋出且未進入其匹配 catch 子句的異常對象數。

有時即使當 std::uncaught_exception() == true(C++17 前) std::uncaught_exceptions() > 0(C++17 起) 時,拋出異常也是安全的。例如,如果棧回溯導致要析構某個對象,那麼該對象的析構函數可以運行拋出異常的代碼,只要在離開析構函數前由某個 catch 塊捕獲該異常即可。

目錄

[編輯] 參數

(無)

[編輯] 返回值

1) 此線程中當前正在進行棧回溯時返回 true,否則返回 false
2) 當前線程中未捕獲的異常對象的數量。

[編輯] 註解

返回 int 的 uncaught_exceptions 的一個使用例子是 boost.log 庫:表達式 BOOST_LOG(logger) << foo(); 首先創建保障對象並記錄其構造函數中的未捕捉異常數。由保障對象的析構函數進行輸出,除非 foo() 拋出了異常(此時析構函數中未捕獲的異常的數量大於構造函數所觀察到的)。

LFTS v3 中的 std::experimental::scope_failstd::experimental::scope_success 依賴 uncaught_exceptions 的功能,因為它們的析構函數需要根據是否在棧回溯中被調用而做不同的事。

功能特性測試 標準 功能特性
__cpp_lib_uncaught_exceptions 201411L (C++17) std::uncaught_exceptions
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr 的異常類型

[編輯] 示例

#include <exception>
#include <iostream>
#include <stdexcept>
 
struct Foo
{
    char id{'?'};
    int count = std::uncaught_exceptions();
 
    ~Foo()
    {
        count == std::uncaught_exceptions()
            ? std::cout << "正常调用 " << id << "~Foo()\n"
            : std::cout << "在栈回溯中调用 " << id << "~Foo()\n");
    }
};
 
int main()
{
    Foo f{'f'};
 
    try
    {
        Foo g{'g'};
        std::cout << "抛出异常\n";
        throw std::runtime_error("测试异常");
    }
    catch (const std::exception& e)
    {
        std::cout << "捕获到异常:" << e.what() << '\n';
    }
}

可能的輸出:

抛出异常
在栈回溯中调用 g.~Foo()
捕获到异常:测试异常
正常调用 f.~Foo()

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 出版時的行為 正確行為
LWG 70 C++98 uncaught_exception() 的異常說明缺失 補充說明 throw()

[編輯] 參閱

異常處理失敗時調用的函數
(函數) [編輯]
處理異常對象的共享指針類型
(typedef) [編輯]
捕獲當前異常到 std::exception_ptr 之中
(函數) [編輯]

[編輯] 外部鏈接

1.  GOTW 問題 47 :未捕捉異常
2.  std::uncaught_exceptions 的基本原理 (N4125)