Namespaces
Variants

std::uncaught_exception, std::uncaught_exceptions

ja.cppreference.net より
(cpp/error/exception/uncaught exception からリダイレクトされました)
 
 
 
ヘッダ <exception>
bool uncaught_exception() throw();
で定義 (1) (C++11 まで)
bool uncaught_exception() noexcept;
(C++11 から)
(C++17 で非推奨)
(C++20 で削除)
int uncaught_exceptions() noexcept;
(2) (C++17 から)
(C++26 から constexpr)
1) 現行スレッドに生存例外オブジェクトが存在するかどうかを検出します。つまり、例外が投げられるか再スローされ、まだ一致する catch 節に入っていないかどうか、std::terminate または std::unexpected に入っていないかどうかです。言い換えると、std::uncaught_exception は スタックアンワインディング が現在進行中であるかどうかを検出します。
2) 現行スレッドで投げられるか再スローされ、まだ一致する catch 節に入っていない例外の数を検出します。

例外を投げることが安全な場合もあります。std::uncaught_exception() == true(C++17 まで) std::uncaught_exceptions() > 0(C++17 から)。例えば、スタックアンワインディング によってオブジェクトが破棄される場合、そのオブジェクトのデストラクタは、例外がデストラクタを抜ける前に何らかの catch ブロックでキャッチされる限り、例外を投げるコードを実行できます。

戻り値

1) true このスレッドでスタック巻き戻しが現在進行中の場合は、 false それ以外の場合。
2) 現在のスレッドにおける未捕捉例外オブジェクトの数。

注記

intを返す uncaught_exceptions が使用される例の一つは boost.log ライブラリです:式 BOOST_LOG ( logger ) << foo ( ) ; は最初にガードオブジェクトを作成し、そのコンストラクタで未捕捉例外の数を記録します。出力はガードオブジェクトのデストラクタで実行されます(ただし foo ( ) が例外をスローした場合を除く。この場合、デストラクタでの未捕捉例外の数はコンストラクタで観測された数より多くなります)。

std::experimental::scope_fail および std::experimental::scope_success はLFTS v3において uncaught_exceptions の機能に依存しています。これは、これらのデストラクタがスタックアンワインディング中に呼び出されるかどうかに応じて異なる処理を行う必要があるためです。

機能テスト マクロ 値 標準 機能
__cpp_lib_uncaught_exceptions 201411L (C++17) std::uncaught_exceptions
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr 例外型の

例

#include <exception>
#include <iostream>
#include <stdexcept>
struct Foo
{
    char id{'?'};
    int count = std::uncaught_exceptions();
    ~Foo()
    {
        count == std::uncaught_exceptions()
            ? std::cout << id << ".~Foo() called normally\n"
            : std::cout << id << ".~Foo() called during stack unwinding\n";
    }
};
int main()
{
    Foo f{'f'};
    try
    {
        Foo g{'g'};
        std::cout << "Exception thrown\n";
        throw std::runtime_error("test exception");
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception caught: " << e.what() << '\n';
    }
}

出力例:

Exception thrown
g.~Foo() called during stack unwinding
Exception caught: test exception
f.~Foo() called normally

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 70 C++98 uncaught_exception()の例外仕様が欠落していた throw()として指定

関連項目

例外処理が失敗したときに呼び出される関数
(関数)
例外オブジェクトを扱うための共有ポインタ型
(typedef)
現在の例外を std::exception_ptr にキャプチャする
(関数)

外部リンク

1. GOTW issue 47: キャッチされない例外
2. std::uncaught_exceptions の理論的根拠 (N4125)