C++ 参考手册

位置:首页 > C++ 参考手册 >错误处理 > std::current_exception

定义于头文件 <exception>
std::exception_ptr current_exception() noexcept;
(C++11 起)

若在当前异常处理(典型地在 catch 子句中)中调用,则捕获当前异常对象,并创建一个保有该异常对象复制或到该异常对象引用的 std::exception_ptr (依赖于实现)。被引用对象保持合法,只要至少要有一个 exception_ptr 对象引用它。

若此函数的实现要求对 new 的调用且调用失败,则返回地指针将保有到一个 std::bad_alloc 实例的引用。

若此函数的实现要求复制被捕获异常对象,且其复制构造函数抛出异常,则返回的指针将保有到被抛出异常的引用。若该被抛出遗产对象的复制构造函数亦抛出,则返回的指针可能保有到 std::bad_exception 实例的引用,以打断无尽循环。

若函数在无被处理异常时调用,则返回空的 std::exception_ptr

参数

(无)

返回值

保有到异常对象引用,或异常对象副本,或指向 std::bad_alloc 实例,或指向 std::bad_exception 实例的 std::exception_ptr 的实例。

示例

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
 
void handle_eptr(std::exception_ptr eptr) // 按值传递 ok
{
    try {
        if (eptr) {
            std::rethrow_exception(eptr);
        }
    } catch(const std::exception& e) {
        std::cout << "Caught exception \"" << e.what() << "\"\n";
    }
}
 
int main()
{
    std::exception_ptr eptr;
    try {
        std::string().at(1); // 这生成一个 std::out_of_range
    } catch(...) {
        eptr = std::current_exception(); // 捕获
    }
    handle_eptr(eptr);
} // std::out_of_range 的析构函数调用于此,在 ept 析构时

输出:

Caught exception "basic_string::at"

参阅

用于处理异常对象的共享指针类型
(typedef)
从一个 std::exception_ptr 抛出异常
(函数)
从异常对象创建一个std::exception_ptr
(函数模板)
检查当前是否正在进行异常处理
(函数)