개발/WIN32-MFC

[ WIN ] Exception Handler 등록 처리 방법

-=HaeJuK=- 2024. 7. 29. 16:07


SetUnhandledExceptionFilter

설명:

  • 용도: Windows 운영 체제에서 발생하는 하드웨어 예외와 같은 낮은 수준의 예외를 처리하기 위해 사용됩니다.
  • 등록 방법: SetUnhandledExceptionFilter 함수를 호출하여 전역 예외 처리기를 등록합니다.
#include <windows.h>
#include <stdio.h>

LONG WINAPI MyExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo) {
    printf("Unhandled exception occurred! Exception code: 0x%08X\n", ExceptionInfo->ExceptionRecord->ExceptionCode);
    return EXCEPTION_EXECUTE_HANDLER;
}

int main() {
    SetUnhandledExceptionFilter(MyExceptionHandler);

    int* p = NULL;
    *p = 42; // 예외 발생

    return 0;
}

 

 

구조화된 예외 처리 (Structured Exception Handling, SEH)

설명:

  • 용도: 코드 블록 내에서 발생하는 예외를 처리하기 위해 사용되는 Windows의 예외 처리 구조입니다.
  • 등록 방법: __try와 __except 블록을 사용하여 예외 처리기를 정의합니다.
#include <windows.h>
#include <stdio.h>

int main() {
    __try {
        int* p = NULL;
        *p = 42; // 예외 발생
    } __except (EXCEPTION_EXECUTE_HANDLER) {
        printf("Exception occurred!\n");
    }

    return 0;
}

 

 

std::set_terminate 

설명:

  • 용도: C++에서 예외가 catch되지 않았을 때 프로그램이 종료되기 전에 호출될 함수를 설정하기 위해 사용됩니다.
  • 등록 방법: std::set_terminate 함수를 호출하여 전역 종료 처리기를 등록합니다.
#include <iostream>
#include <exception>

void MyTerminateHandler() {
    std::cerr << "Unhandled exception! Program will terminate." << std::endl;
    std::abort();
}

int main() {
    std::set_terminate(MyTerminateHandler);

    try {
        throw std::runtime_error("An error occurred!");
    } catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    throw std::runtime_error("Unhandled exception!"); // 예외 발생

    return 0;
}

 

차이점 

  • 언어 레벨 차이:
    • SetUnhandledExceptionFilter: Windows API (C 언어 기반)에서 제공, 하드웨어 예외 처리.
    • SEH: Windows 환경에서 C/C++ 언어를 사용한 구조화된 예외 처리.
    • std::set_terminate: C++ 표준 라이브러리, C++ 예외 처리 시스템과 통합.
  • 용도 차이:
    • SetUnhandledExceptionFilter: 시스템 레벨의 하드웨어 예외 처리.
    • SEH: 코드 블록 내 특정 예외 처리.
    • std::set_terminate: C++ 예외가 catch되지 않았을 때 호출될 함수 설정.
  • 호출 시점 차이:
    • SetUnhandledExceptionFilter: 운영 체제에서 예외가 발생하고 애플리케이션에서 처리되지 않을 때.
    • SEH: 코드 블록 내에서 예외가 발생할 때.
    • std::set_terminate: C++ 예외가 catch되지 않았을 때.
반응형