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.

Dr. Gut's user avatar

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.

Dr. Gut's user avatar

Dr. Gut

3,54514 silver badges33 bronze badges

im-md18's user avatar

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.

1 Comment

it not let any exception (no matter c++ or not) go out of callback

2026-02-18T21:17:53.067Z+00:00

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.

Dr. Gut's user avatar

Dr. Gut

3,54514 silver badges33 bronze badges

0___________'s user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.