首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::uncaught_exception

Defined in header <exception>

bool uncaught_exception();

(1)

(deprecated in C++17)

int uncaught_exceptions();

(2)

(since C++17)

1%29检测当前线程是否有活动异常对象,即异常已抛出或重新抛出,并且尚未输入匹配的CATCH子句,std::terminatestd::unexpected换句话说,std::uncaught_exception检测堆栈展开是否正在进行中。

2%29检测当前线程中有多少异常已被抛出或重新抛出,但尚未输入它们的匹配CATCH子句。

有时即使在std::uncaught_exception()==true例如,如果堆栈展开导致堆栈分配的对象被解构,则该对象的析构函数可以运行代码,只要异常在转义析构函数之前被某些CATCH块捕获,就会抛出异常。

参数

%280%29

返回值

1%29true如果堆栈展开正在此线程中进行。

2%29当前线程中的未命名异常对象的数量。

例外

(none)

(until C++11)

noexcept specification: noexcept

(since C++11)

注记

一个int返回的示例uncaught_exceptions被使用的是bost.log图书馆:表达BOOST_LOG(logger) << foo();首先,创建一个守护对象,并在构造函数中记录未识别异常的数量。输出由保护对象%27s析构函数执行,除非foo%28%29抛出%28,在这种情况下,析构函数中的未捕获异常数大于构造函数观察到的%29。

二次

代码语言:javascript
复制
#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';
    }
}

二次

产出:

二次

代码语言:javascript
复制
Exception thrown
~Foo() called during stack unwinding
Exception caught: test exception
~Foo() called normally

二次

另见

terminate

function called when exception handling fails (function)

exception_ptr (C++11)

shared pointer type for handling exception objects (typedef)

current_exception (C++11)

captures the current exception in a std::exception_ptr (function)

外部链接

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券