例外処理

構造化例外処理とC++の例外処理
前者はWindows固有の機能,後者はOSを問わずC++言語の機能.

詳しくはここを参照 Windows structured error handling(SEH)
https://docs.microsoft.com/ja-jp/cpp/cpp/structured-exception-handling-c-cpp?view=vs-2019

抜粋:「try-except および try-finally ステートメントは C 言語に対する Microsoft の拡張機能です. ほとんどの場合、SEH ではなく、ISO 標準C++ C++の例外処理を使用することをお勧めします」

つまり,Windowsの構造化例外処理はMS独自の機能で,C++ 例外処理とは別物.そっちを使え,とのこと.

Windows 構造化例外処理

C++でなく,C言語でも使用できるということはメリットかもしれない.

//#include <windows.h>   //  これがなくてもコンパイルできる?
#include <stdio.h>
#include <memory.h>

int main(int argc, char* argv[])
{
    __try {
        printf("Hello World!\n");
        return 0;
    }

//  __try ブロック終了時に呼ばれる
    __finally {
        printf("in __finally\n");
    }
    return 0;
}

例外が発生した際のハンドラを指定する方法.

EXCEPTION_POINTERS structure,EXCEPTION_RECORD structure についてはこちら.

EXCEPTION_POINTERS structure :
https://docs.microsoft.com/ja-jp/windows/win32/api/winnt/ns-winnt-exception_pointers

EXCEPTION_RECORD structure :
https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record

#include <windows.h>
#include <stdio.h>
#include <memory.h>     //  memcpy()

LONG WINAPI UEF( PEXCEPTION_POINTERS pExc )
{
    printf ("in Unhandled Exception Filter, code = 0x%x\n", pExc->ExceptionRecord->ExceptionCode);
    return EXCEPTION_EXECUTE_HANDLER;
}


int main(int argc, char* argv[])
{
    //  例外ハンドラの指定
    ::SetUnhandledExceptionFilter (UEF);

    __try {
        printf("Hello World!\n");

//      何か runtime error, 問題を発生させる
//      memcpy(NULL,NULL,1000);		//  (1)
        int i=0; int j=1/i;			//  (2)
        return 0;
    }

    __finally {
        printf("in __finally\n");
    }
    return 0;
}

実行例
(1) NULLポインタ
Hello World!
in Unhandled Exception Filter, code = 0xc0000005
in __finally

(2) 0割り算
Hello World!
in Unhandled Exception Filter, code = 0xc0000094
in __finally