ARTICLE AD BOX
Suppose, I have a try/catch in the wWinMain() function, which calls some Windows API functions, e.g. CreateWindowExW(), GetMessageW(), TranslateMessage(), DispatchMessageW(). The Windows API will call back my WndProc().
Can I throw a C++ exception inside WndProc(), and catch it in wWinMain()?
Both functions are authored by me, but the exception would go through Windows DLLs.
3,54514 silver badges33 bronze badges
4
No, don't let a C++ exception escape from WndProc to be caught in wWinMain.
The exception would unwind through user32.dll, and that is not guaranteed or supported. It may work sometimes, but it can also crash or behave unpredictably.
Instead: catch inside WndProc, store the error (e.g., with std::exception_ptr), call PostQuitMessage, and then rethrow it in wWinMain after the message loop ends.
3,54514 silver badges33 bronze badges
New contributor
im-md18 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
No. Instead, do one of the following:
Catch in WndProc and signal to the loop.
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { try { // ... your normal handling ... return DefWindowProcW(hWnd, msg, wParam, lParam); } catch (...) { // record the exception somewhere (thread-local/global) // then ask the message loop to exit PostQuitMessage(1); return 0; } }Then, in wWinMain, after the message loop ends, rethrow if you want. Store std::exception_ptr (thread-local is fine if everything is on the UI thread) after GetMessageW returns 0 / -1, check it and std::rethrow_exception.
Post a custom message and handle it in the loop Instead of throwing, set a flag/std::exception_ptr and PostMessageW(hwnd, WM_APP+x, ...), see WM_APP.
3,54514 silver badges33 bronze badges
72.3k4 gold badges42 silver badges95 bronze badges
Explore related questions
See similar questions with these tags.

