命名空间
变体
操作

std::throw_with_nested

来自 cppreference.cn
< cpp‎ | 错误
定义于头文件 <exception>
template< class T >
[[noreturn]] void throw_with_nested( T&& t );
(C++11 起)
(C++26 起为 constexpr)

如果 std::decay<T>::type 是非 final 非 union 类类型,且既不是 std::nested_exception 也不是派生自 std::nested_exception,则抛出未指定类型的异常,该异常公开派生自 std::nested_exceptionstd::decay<T>::type,并从 std::forward<T>(t) 构造。`nested_exception` 基类的默认构造函数调用 std::current_exception,如果存在,则将当前处理的异常对象捕获到 std::exception_ptr 中。

否则,抛出 std::forward<T>(t)

要求 std::decay<T>::type可复制构造的(CopyConstructible)

目录

[编辑] 参数

t - 要抛出的异常对象

[编辑] 注解

特性测试 标准 特性
__cpp_lib_constexpr_exceptions 202411L (C++26) 异常类型的 constexpr

[编辑] 示例

演示通过嵌套异常对象的构造和递归。

#include <exception>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
 
// prints the explanatory string of an exception. If the exception is nested,
// recurses to print the explanatory string of the exception it holds
void print_exception(const std::exception& e, int level =  0)
{
    std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n';
    try
    {
        std::rethrow_if_nested(e);
    }
    catch (const std::exception& nestedException)
    {
        print_exception(nestedException, level + 1);
    }
    catch (...) {}
}
 
// sample function that catches an exception and wraps it in a nested exception
void open_file(const std::string& s)
{
    try
    {
        std::ifstream file(s);
        file.exceptions(std::ios_base::failbit);
    }
    catch (...)
    {
        std::throw_with_nested(std::runtime_error("Couldn't open " + s));
    }
}
 
// sample function that catches an exception and wraps it in a nested exception
void run()
{
    try
    {
        open_file("nonexistent.file");
    }
    catch (...)
    {
        std::throw_with_nested(std::runtime_error("run() failed"));
    }
}
 
// runs the sample function above and prints the caught exception
int main()
{
    try
    {
        run();
    }
    catch (const std::exception& e)
    {
        print_exception(e);
    }
}

可能的输出

exception: run() failed
 exception: Couldn't open nonexistent.file
  exception: basic_ios::clear

[编辑] 参阅

用于捕获和存储当前异常的 mixin 类型
(类) [编辑]
std::nested_exception 抛出异常
(函数模板) [编辑]