std::current_exception
| ヘッダー <exception> で定義 |
||
std::exception_ptr current_exception() noexcept; |
(C++11以降) (C++26 以降 constexpr) |
|
例外処理中(通常は catch 節内)に呼び出された場合、現在の例外オブジェクトをキャプチャし、その例外オブジェクトのコピーまたは参照を保持する std::exception_ptr を作成します(実装によります)。参照されるオブジェクトは、それを参照する exception_ptr オブジェクトが存在する限り、少なくとも有効なままです。
この関数の実装が new の呼び出しを必要とし、その呼び出しが失敗した場合、返されるポインタは std::bad_alloc のインスタンスへの参照を保持します。
この関数の実装がキャプチャされた例外オブジェクトのコピーを必要とし、そのコピーコンストラクタが例外をスローした場合、返されるポインタはスローされた例外への参照を保持します。スローされた例外オブジェクトのコピーコンストラクタもスローした場合、無限ループを回避するために、返されるポインタは std::bad_exception のインスタンスへの参照を保持する場合があります。
例外が処理されていないときにこの関数が呼び出されると、空の std::exception_ptr が返されます。
この関数は、std::terminate の呼び出しを引き起こした例外を取得するために、std::terminate_handler 内で呼び出すことができます。
目次 |
[編集] 戻り値
例外オブジェクトへの参照、または例外オブジェクトのコピー、または std::bad_alloc のインスタンス、または std::bad_exception のインスタンスを保持する std::exception_ptr のインスタンス。
[編集] 備考
Itanium C++ ABI に従う実装(GCC、Clangなど)では、例外はスローされるときにヒープに割り当てられ(場合によっては std::bad_alloc を除く)、この関数は以前に割り当てられたオブジェクトを参照するスマートポインタを作成するだけです。MSVCでは、例外はスローされるときにスタックに割り当てられ、この関数はヒープ割り当てを実行し、例外オブジェクトをコピーします。
マネージCLR環境のWindows [1] では、現在の例外がマネージ例外である場合、実装は std::bad_exception を格納します ([2])。catch(...) がマネージ例外も捕捉することに注意してください。
#include <exception> int main() { try { throw gcnew System::Exception("Managed exception"); } catch (...) { std::exception_ptr ex = std::current_exception(); try { std::rethrow_exception(ex); } catch (std::bad_exception const &) { // This will be printed. std::cout << "Bad exception" << std::endl; } } }
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_lib_constexpr_exceptions |
202411L |
(C++26) | constexpr for exception types |
[編集] 例
#include <exception> #include <iostream> #include <stdexcept> #include <string> void handle_eptr(std::exception_ptr eptr) // passing by value is OK { try { if (eptr) std::rethrow_exception(eptr); } catch(const std::exception& e) { std::cout << "Caught exception: '" << e.what() << "'\n"; } } int main() { std::exception_ptr eptr; try { [[maybe_unused]] char ch = std::string().at(1); // this generates a std::out_of_range } catch(...) { eptr = std::current_exception(); // capture } handle_eptr(eptr); } // destructor for std::out_of_range called here, when the eptr is destructed
実行結果の例
Caught exception: 'basic_string::at: __n (which is 1) >= this->size() (which is 0)'
[編集] 関連項目
| (C++11) |
例外オブジェクトを扱うための共有ポインタ型 (typedef) |
| (C++11) |
std::exception_ptr から例外を送出する (関数) |
| (C++11) |
例外オブジェクトから std::exception_ptr を作成する (関数テンプレート) |
| (C++17で非推奨)(C++20で削除*) |
例外処理が現在進行中であるかを確認する (関数) |