Namespaces
Variants

std:: throw_with_nested

From cppreference.net
ヘッダーで定義 <exception>
template < class T >
[ [ noreturn ] ] void throw_with_nested ( T && t ) ;
(C++11以降)
(constexprはC++26以降)

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 CopyConstructible であることを要求します。

目次

パラメータ

t - スローする例外オブジェクト

注記

機能テスト マクロ 標準 機能
__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

関連項目

現在の例外を捕捉して格納するためのミックスイン型
(クラス)
std::nested_exception から例外を再スローする
(関数テンプレート)