名前空間
変種
操作

std::nested_exception

From cppreference.com
< cpp‎ | error
 
 
 
ヘッダー <exception> で定義
class nested_exception;
(C++11以降)

std::nested_exception は、現在の例外をキャプチャして格納できるポリモーフィックなミックスインクラスであり、任意の型の例外を互いにネストさせることが可能になります。

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

(C++26以降)

目次

[編集] メンバ関数

nested_exception を構築します
(public member function)
ネストされた例外を破棄します
(仮想 public メンバ関数)
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 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

[編集] 関連項目

例外オブジェクトを扱うための共有ポインタ型
(typedef) [編集]
std::nested_exception をミックスインして引数をスローします
(関数テンプレート) [編集]
std::nested_exception から例外をスローします
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)