std::uncaught_exception, std::uncaught_exceptions

定义于头文件 <exception>
(1)
bool uncaught_exception();
(C++11 前)
bool uncaught_exception() noexcept;
(C++11 起)
(C++17 中弃用)
int uncaught_exceptions() noexcept;
(2) (C++17 起)
1) 检测当前线程是否有生存的异常对象,即被抛出或重抛出且未进入匹配的 catch 子句、 std::terminatestd::unexpected 的异常。换言之,std::uncaught_exception 检测当前是否在进行栈回溯。
2) 检测当前线程已经抛出或重抛出且未进入其匹配 catch 子句的异常对象数。

有时抛出异常是安全的,即使当 std::uncaught_exception() == true 。例如,若栈回溯导致要析构拥有自动存储期的对象,则该对象的析构函数可以运行抛出异常的代码,只要在离开析构函数前为某 catch 块捕捉该异常。

目录

参数

(无)

返回值

1) 若此线程中当前正在进行栈回溯则为 true
2) 当前线程中的为捕捉异常对象数。

注意

返回 int 的 uncaught_exceptions 的一个使用例子是 boost.log 库:表达式 BOOST_LOG(logger) << foo(); 首先创建保障对象并记录其构造函数中的未捕捉异常数。由保障对象的析构函数进行输出,除非 foo() 抛出(该情况下析构函数中未捕捉异常的数量大于构造函数所观察到的)

示例

#include <iostream>
#include <exception>
#include <stdexcept>
 
struct Foo {
    ~Foo() {
        if (std::uncaught_exception()) {
            std::cout << "~Foo() called during stack unwinding\n";
        } else {
            std::cout << "~Foo() called normally\n";
        }
    }
};
int main()
{
    Foo f;
    try {
        Foo f;
        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
~Foo() called during stack unwinding
Exception caught: test exception
~Foo() called normally

参阅

异常处理失败时调用的函数
(函数)
处理异常对象的共享指针类型
(typedef)
std::exception_ptr 中捕获当前异常
(函数)

外部链接

版本历史

  • (当前 | 先前 2017年12月15日 (五) 06:51Fruderica讨论 | 贡献 . . (2,727字节) (0). . (wording) (撤销)
  • 当前 | 先前 2017年12月15日 (五) 01:29Kafuuchino讨论 | 贡献. . (2,727字节) (+6). . (撤销)
  • 当前 | 先前 2017年12月15日 (五) 01:25Kafuuchino讨论 | 贡献. . (2,721字节) (+26). . (撤销)
  • 当前 | 先前 2017年8月26日 (六) 22:11Fruderica讨论 | 贡献 . . (2,695字节) (-36). . (撤销)
  • 当前 | 先前 2017年5月17日 (三) 08:12Fruderica讨论 | 贡献. . (2,731字节) (+139). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 16:45P12bot讨论 | 贡献 . . (2,592字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 08:06P12bot讨论 | 贡献 . . (2,592字节) (-32). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 13:52P12bot讨论 | 贡献 . . (2,624字节) (+289). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 10:37P12讨论 | 贡献 . . (2,335字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (2,335字节) (-54). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 13:25P12讨论 | 贡献 . . (2,389字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (2,389字节) (+2,389). . (Translated from the English version using Google Translate)