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_handler 内で呼び出され、 std::terminate の呼び出しを引き起こした例外を取得するために使用できます。
目次 |
戻り値
例外オブジェクトへの参照、または例外オブジェクトのコピー、あるいは std::bad_alloc のインスタンス、または std::bad_exception のインスタンスを保持する std::exception_ptr のインスタンス。
注記
Itanium C++ ABI に準拠する実装(GCC、Clangなど)では、例外はスロー時にヒープ上に割り当てられます(一部の場合を除く std::bad_alloc )。この関数は、事前に割り当てられたオブジェクトを参照するスマートポインタを作成するだけです。MSVCでは、例外はスロー時にスタック上に割り当てられ、この関数はヒープ割り当てを実行して例外オブジェクトをコピーします。
WindowsのマネージドCLR環境では [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 &) { // これは出力されます std::cout << "Bad exception" << std::endl; } } }
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_constexpr_exceptions
|
202411L
|
(C++26) | constexpr 例外型のためのconstexpr |
例
#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
から例外をスローする
(function) |
|
(C++11)
|
例外オブジェクトから
std::exception_ptr
を作成する
(function template) |
|
(
removed in C++20*
)
(C++17)
|
例外処理が現在進行中かどうかをチェックする
(function) |