Namespaces
Variants

std:: set_terminate

From cppreference.net
헤더 파일에 정의됨 <exception>
(C++11 이전)
(C++11 이후)

f 를 새로운 전역 terminate handler 함수로 설정하고, 이전에 설치된 std::terminate_handler 를 반환합니다. f 는 호출자에게 제어를 반환하지 않고 프로그램 실행을 종료해야 하며, 그렇지 않을 경우 동작은 정의되지 않습니다.

이 함수는 스레드 안전합니다. std::set_terminate 에 대한 모든 호출은 이후의 std::set_terminate std::memory_order ) 호출과 동기화됩니다 (참조: std::get_terminate ).

(C++11부터)

목차

매개변수

f - std::terminate_handler 타입의 함수 포인터, 또는 null 포인터

반환값

이전에 설치된 종료 처리기, 또는 설치된 것이 없을 경우 null 포인터 값.

예제

#include <cstdlib>
#include <exception>
#include <iostream>
int main()
{
    std::set_terminate([]()
    {
        std::cout << "Unhandled exception\n" << std::flush;
        std::abort();
    });
    throw 1;
}

가능한 출력:

Unhandled exception
bash: line 7:  7743 Aborted                 (core dumped) ./a.out

종료 핸들러는 시작된 스레드에서도 작동하므로, 스레드 함수를 try / catch 블록으로 감싸는 대안으로 사용할 수 있습니다. 다음 예제에서는 예외가 처리되지 않았기 때문에 std::terminate 가 호출됩니다.

#include <iostream>
#include <thread>
void run()
{
    throw std::runtime_error("Thread failure");
}
int main()
{
    try
    {
        std::thread t{run};
        t.join();
        return EXIT_SUCCESS;
    }
    catch (const std::exception& ex)
    {
        std::cerr << "Exception: " << ex.what() << '\n';
    }
    catch (...)
    {
        std::cerr << "Unknown exception caught\n";
    }
    return EXIT_FAILURE;
}

가능한 출력:

terminate called after throwing an instance of 'std::runtime_error'
  what():  Thread failure
Aborted (core dumped)

terminate 핸들러의 도입으로, 비-메인 스레드에서 발생한 예외를 분석하고 정상적으로 종료를 수행할 수 있습니다.

#include <iostream>
#include <thread>
class foo
{
public:
    foo() { std::cerr << "foo::foo()\n"; }
    ~foo() { std::cerr << "foo::~foo()\n"; }
};
// 정적 객체, 종료 시 소멸자 호출 예상
foo f;
void run()
{
    throw std::runtime_error("Thread failure");
}
int main()
{
    std::set_terminate([]()
    {
        try
        {
            std::exception_ptr eptr{std::current_exception()};
            if (eptr)
            {
                std::rethrow_exception(eptr);
            }
            else
            {
                std::cerr << "Exiting without exception\n";
            }
        }
        catch (const std::exception& ex)
        {
            std::cerr << "Exception: " << ex.what() << '\n';
        }
        catch (...)
        {
            std::cerr << "Unknown exception caught\n";
        }
        std::exit(EXIT_FAILURE);
    });
    std::thread t{run};
    t.join();
}

출력:

foo::foo()
Exception: Thread failure
foo::~foo()

참고 항목

예외 처리 실패 시 호출되는 함수
(함수)
현재 terminate_handler를 얻음
(함수)
std::terminate 에 의해 호출되는 함수의 타입
(typedef)