Namespaces
Variants

std:: nested_exception

From cppreference.net
ヘッダーで定義 <exception>
class nested_exception ;
(C++11以降)

std::nested_exception は、現在の例外を捕捉して保存することが可能な多態的ミックスインクラスであり、任意の型の例外を互いにネストさせることを可能にします。

std::nested_exception のすべてのメンバー関数は constexpr です。

(C++26以降)

目次

メンバー関数

nested_exceptionを構築する
(public member function)
[virtual]
nested exceptionを破棄する
(virtual public member function)
nested_exceptionの内容を置き換える
(public member function)
格納された例外をスローする
(public member function)
格納された例外へのポインタを取得する
(public member function)

非メンバー関数

引数を std::nested_exception と共に送出する
(関数テンプレート)
std::nested_exception から例外を再送出する
(関数テンプレート)

注記

機能テスト マクロ 標準 機能
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr 例外型のための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

関連項目

例外オブジェクトを扱うための共有ポインタ型
(typedef)
引数を std::nested_exception と共に送出する
(関数テンプレート)
std::nested_exception から例外を送出する
(関数テンプレート)