最終更新日時:
が更新

履歴 編集

function template
<exception>

std::throw_with_nested(C++11)

namespace std {
  template <class T>
  [[noreturn]] void throw_with_nested(T&& t); // (1) C++11
}

概要

現在処理中の例外を入れ子にした例外を送出する

事前条件

Udecay_t<T> として、型Uがコピー構築可能(Cpp17CopyConstructible)の要件を満たすこと。

例外

Udecay_t<T> とする。

戻り値

この関数は決して返らない

#include <iostream>
#include <exception>
#include <memory>

struct inner_error : public std::exception {};
struct outer_error : public std::nested_exception {};

// 現在の例外を取得
template <class T>
std::shared_ptr<T> get_exception(std::exception_ptr ep)
{
  try {
    std::rethrow_exception(ep);
  }
  catch (T& e) {
    return std::shared_ptr<T>(new T(e));
  }
  catch (...) {}
  return nullptr;
}

// 入れ子になってる例外を取得
template <class T>
std::shared_ptr<T> get_nested_exception(std::nested_exception& ex)
{
  try {
    std::rethrow_if_nested(ex); // 入れ子になってる例外を送出
  }
  catch (T& e) {
    return std::shared_ptr<T>(new T(e));
  }
  catch (...) {}
  return nullptr;
}

int main()
{
  try {
    try {
      throw inner_error();
    }
    catch (...) {
      // inner_errorを入れ子にしてouter_errorを送出
      std::throw_with_nested(outer_error());
    }
  }
  catch (...) {
    // 外側の例外を取得
    if (std::shared_ptr<outer_error> outer = get_exception<outer_error>(std::current_exception())) {
      std::cout << "outer" << std::endl;

      // 入れ子になった例外を取得
      if (std::shared_ptr<inner_error> inner = get_nested_exception<inner_error>(*outer)) {
        std::cout << "inner" << std::endl;
      }
    }
  }
}

出力

outer
inner

バージョン

言語

  • C++11

処理系

関連項目

参照

  • P3842R2 A conservative fix for constexpr uncaught_exceptions() and current_exception()
    • C++26の策定中にconstexprが追加されたが、本提案文書により巻き戻された (C++29で再検討予定)
  • LWG Issue 2483. throw_with_nested() should use is_final
    • ラップするかどうかの判定にis_finalによる条件が追加され、final指定されたクラスも引数に取れるようになった
    • この修正は欠陥報告(DR)であり、C++11以降に遡及して適用される。final指定されたクラスから派生した型を送出するという元の規定は実装不可能であり、処理系は当初から派生させずにそのまま送出していたため、これと異なる観測可能な挙動が出荷されていたわけではない
  • LWG Issue 2855. std::throw_with_nested("string_literal")
    • 判定にdecay_t<T>を用いるよう変更され、文字列リテラルや関数など(配列型・関数型)を渡せることが明確化された
    • この修正は欠陥報告(DR)であり、C++11以降に遡及して適用される。配列型・関数型を排除していた元の要件は文言上の欠陥であり、処理系は当初からdecay後の型で動作していたため