命名空间
变体
操作

std::uncaught_exception, std::uncaught_exceptions

来自 cppreference.cn
< 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 起)
(constexpr 自 C++26 起)
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(); 首先创建一个 guard 对象,并在其构造函数中记录未捕获异常的数量。输出由 guard 对象的析构函数执行,除非 foo() 抛出异常(在这种情况下,析构函数中未捕获异常的数量将大于构造函数观察到的数量)。

std::experimental::scope_failstd::experimental::scope_success 在 LFTS v3 中依赖于 uncaught_exceptions 的功能,因为它们的析构函数需要根据是否在堆栈回退期间调用来执行不同的操作。

特性测试 Std 特性
__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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 70 C++98 uncaught_exception() 的异常规范缺失 指定为 throw()

[编辑] 参见

异常处理失败时调用的函数
(函数) [编辑]
用于处理异常对象的共享指针类型
(类型定义) [编辑]
std::exception_ptr 中捕获当前异常
(函数) [编辑]

[编辑] 外部链接

1.  GOTW issue 47: Uncaught Exceptions
2.  Rationale for std::uncaught_exceptions (N4125)