std::nested_exception

来自cppreference.com
P12留言 | 贡献2012年10月25日 (四) 21:25的版本 (1个修订: Translate from the English version)

<metanoindex/>

在标头 <exception> 定义
class nested_exception;
(C++11 起)
std::nested_exceptions是一个多态的混合类,它可以捕获和存储当前的异常,它可以任意类型的异常巢内相互.
原文:
std::nested_exceptions is a polymorphic mixin class which can capture and store the current exception, making it possible to nest exceptions of arbitrary types within each other.
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

。成员函数。

。构造一个nested_exception。
原文:
constructs a nested_exception
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

(公开成员函数)
。解构嵌套异常。
原文:
destructs a nested exception
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

(虚公开成员函数)
。替换内容的nested_exception。
原文:
replaces the contents of a nested_exception
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

(公开成员函数)
。抛出的存储异常。
原文:
throws the stored exception
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

(公开成员函数)
。获得一个指针所存储的异常。
原文:
obtains a pointer to the stored exception
文本通过谷歌翻译机器翻译。
你可以帮忙校正和验证翻译。点击此处查看指示。

(公开成员函数)

。为例。

演示构造并通过 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

。另请参阅。

Template:cpp/error/dcl list exception ptr