名前空間
変種
操作

std::throw_with_nested

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

If std::decay<T>::type が、`std::nested_exception` ではなく、かつ `std::nested_exception` から派生していない、最終クラスでない(`final` ではない)非共用体(non-union)クラス型である場合、`std::nested_exception` と `std::decay<T>::type` の両方から公開派生(publicly derived)しており、`std::forward<T>(t)` から構築される、指定されていない型の例外をスローします。`nested_exception` 基底クラスのデフォルトコンストラクタは、`std::current_exception` を呼び出し、現在処理中の例外オブジェクトがあれば、それを `std::exception_ptr` にキャプチャします。

それ以外の場合、`std::forward<T>(t)` をスローします。

Requires that std::decay<T>::type is CopyConstructible.

目次

[編集] パラメータ

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

[編集] 注記

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

[編集] 関連項目

現在の例外をキャプチャして格納するためのmixin型
(クラス) [編集]
std::nested_exception から例外を送出する
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)