Template:cpp/error/example nested exception

来自cppreference.com

演示构造并通过 nested_exception 对象递归。

#include <exception>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
 
// 打印异常的解释性字符串。若异常内嵌,则递归打印其保有的异常的解释性字符串
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 (...) {}
}
 
// 示例函数,捕捉异常并将其包装于 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));
    }
}
 
// 示例函数,捕捉异常并将其包装于 nested_exception
void run()
{
    try
    {
        open_file("nonexistent.file");
    }
    catch (...)
    {
        std::throw_with_nested(std::runtime_error("run() failed"));
    }
}
 
// 运行上述实例函数并打印捕捉的异常
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