std::uncaught_exception, std::uncaught_exceptions
來自 cppreference.com
定義於標頭檔案 <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::terminate 或 std::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(); 首先建立一個 guard 物件並在其建構函式中記錄未捕獲異常的數量。輸出由 guard 物件的解構函式執行,除非 foo() 丟擲異常(在這種情況下,解構函式中未捕獲異常的數量將大於建構函式中觀察到的數量)。
LFTS v3 中的 std::experimental::scope_fail 和 std::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() called normally\n" : std::cout << id << ".~Foo() called during stack unwinding\n"; } }; int main() { Foo f{'f'}; try { Foo g{'g'}; std::cout << "Exception thrown\n"; throw std::runtime_error("test exception"); } catch (const std::exception& e) { std::cout << "Exception caught: " << e.what() << '\n'; } }
可能的輸出
Exception thrown g.~Foo() called during stack unwinding Exception caught: test exception f.~Foo() called normally
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 70 | C++98 | uncaught_exception() 的異常規範缺失 |
指定為 throw() |
[編輯] 另請參閱
異常處理失敗時呼叫的函式 (函式) | |
(C++11) |
用於處理異常物件的共享指標型別 (typedef) |
(C++11) |
將當前異常捕獲到 std::exception_ptr 中 (函式) |
[編輯] 外部連結
1. | GOTW issue 47: 未捕獲異常 |
2. | std::uncaught_exceptions 的原理 (N4125) |