Namespaces
Variants

std:: current_exception

From cppreference.net
헤더 파일에 정의됨 <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::exception_ptr 인스턴스를 보유하는 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 예외 타입

예제

#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)'

참고 항목

예외 객체를 처리하기 위한 공유 포인터 타입
(typedef)
std::exception_ptr 로부터 예외를 다시 던짐
(function)
예외 객체로부터 std::exception_ptr 를 생성함
(function template)
( removed in C++20* ) (C++17)
현재 예외 처리 중인지 확인함
(function)