[Win32 C++] Exception Handling Implementation using Win32 in C++

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,843
Here's a simple way of implementing exception handling using Win32 in C++. Note that when using Win32, the API uses UTF-16, not UTF-8, for its Unicode interface. This is mainly because of historical reasons.

Therefore, in order to work with this, you need to use wide strings in C++.

I also added OutputDebugStringA to emphasize that it outputs ANSI strings, and also to output it to the debugger's output window/view.

Code:
#include <Windows.h>
#include <string>
#include <sstream>
#include <exception>
#include <comdef.h>

class Foo : public std::runtime_error {
public:
    std::wstring errorMessageW;
    std::string errorMessageA;

    Foo(HRESULT result, const char* funcName) : std::runtime_error("Unexpected error") {
        std::wstringstream functionName;
        functionName << funcName;
        _com_error error(result);
        std::wstring message = error.ErrorMessage();
        this->errorMessageW = std::wstring(functionName.str() + L" has failed with error message: " + message + L"\n");
        this->errorMessageA = std::string(this->errorMessageW.begin(), this->errorMessageW.end());
    }

    const char* what() const throw() override {
        return this->errorMessageA.c_str();
    }
};


int WINAPI WinMain(HINSTANCE h, HINSTANCE nu, LPSTR s, int c) {
    HRESULT result = S_OK;
    try {
        throw Foo(result, __func__);
    }
    catch (Foo e) {
        MessageBox(nullptr, e.errorMessageW.c_str(), L"Error", MB_OK);
        OutputDebugStringA(e.what());
    }
    return 0;
}

Output message is given below:

Code:
WinMain has failed with error message: The operation completed successfully.
 
Last edited:
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top