std:: uncaught_exception, std:: uncaught_exceptions
|
ヘッダーで定義
<exception>
|
||
| (1) | ||
|
bool
uncaught_exception
(
)
throw
(
)
;
|
(C++11まで) | |
|
bool
uncaught_exception
(
)
noexcept
;
|
(C++11から)
(C++17で非推奨) (C++20で削除) |
|
|
int
uncaught_exceptions
(
)
noexcept
;
|
(2) |
(C++17から)
(C++26からconstexpr) |
std::uncaught_exception
は
スタックアンワインディング
が現在進行中かどうかを検出します。
時には、たとえ std :: uncaught_exception ( ) == true (C++17まで) std :: uncaught_exceptions ( ) > 0 (C++17以降) であっても、例外を安全にスローできる場合があります。例えば、 スタックアンワインディング によってオブジェクトが破棄される場合、そのオブジェクトのデストラクタは、例外がデストラクタを抜ける前に何らかのcatchブロックで捕捉される限り、例外をスローするコードを実行できます。
目次 |
パラメータ
(なし)
戻り値
注記
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()
として指定
|
関連項目
|
例外処理が失敗したときに呼び出される関数
(関数) |
|
|
(C++11)
|
例外オブジェクトを扱うための共有ポインタ型
(typedef) |
|
(C++11)
|
現在の例外を
std::exception_ptr
にキャプチャする
(関数) |
外部リンク
| 1. | GOTW issue 47: キャッチされない例外 |
| 2. |
std::uncaught_exceptions
の理論的根拠
(N4125)
|