命名空间
变体
操作

std::throw_with_nested

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

如果 std::decay<T>::type 是非 final 非联合类类型,且既非 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>::typeCopyConstructible

目录

[编辑] 参数

t - 要抛出的异常对象

[编辑] 注解

特性测试 Std 特性
__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

[编辑] 参见

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