Namespaces
Variants

std:: throw_with_nested

From cppreference.net
定义于头文件 <exception>
template < class T >
[ [ noreturn ] ] void throw_with_nested ( T && t ) ;
(C++11 起)
(C++26 起为 constexpr)

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

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

要求 std:: decay < T > :: type 满足 可复制构造 要求。

目录

参数

t - 要抛出的异常对象

注释

功能测试 标准 功能
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr for exception types

示例

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

#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 中的异常
(函数模板)