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
(函数模板)

版本历史

  • (当前 | 先前 2017年5月17日 (三) 09:39Fruderica讨论 | 贡献. . (1,518字节) (-1,407). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:45P12bot讨论 | 贡献 . . (2,925字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:02P12bot讨论 | 贡献 . . (2,925字节) (-41). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 16:56P12bot讨论 | 贡献 . . (2,966字节) (+281). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 11:35P12讨论 | 贡献 . . (2,685字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 07:00TranslationBot讨论 | 贡献. . (2,685字节) (-60). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:24P12讨论 | 贡献 . . (2,745字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 13:00TranslationBot讨论 | 贡献. . (2,745字节) (+2,745). . (Translated from the English version using Google Translate)