Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in WindowProc

Is it possible to catch error inside WindowProc callback? try / catch doesnt work. Looks like __try __except and also hardware exception (AV, for example) doesnt work also.


Update:

I figured out that indeed this is possible to throw exception in WindowProc callback and catch it with catch block outside WindowProc. Tested and works on Windows XP x86. I found releated question 64bit exceptions in WndProc silently fail The problem seems only exist on Windows 7 x64 (and according to that question on other x64 Windows versions too).

So the question is it possible somehow to throw exception in WindowProc and catch it with catch block outside WindowProc? I installed microsoft hotfix, set DisableUserModeCallbackFilter to 1 in registry and best I get is FATAL_USER_CALLBACK_EXCEPTION, not my exception.

like image 842
Demion Avatar asked Feb 01 '13 09:02

Demion


2 Answers

The MSDN documentation for WindowProc has detailed info on exceptions thrown/propagated from WindowProc. It seems that exceptions are only propagated in 32-bit versions of Windows.

However, your original question is different from the question in your update. The first one was about catching exceptions in WindowProc, and that will work fine always. The second one is about throwing exceptions from WindowProc.

I'm not sure about the usefulness/necessity of the second one. A window procedure is normally called as a result of:

  1. Calling DispatchMessage in the message loop. There's no need to throw an exception in this case because doing so would just cause the application to exit. If you encounter an error that should cause the application to exit, just call PostQuitMessage(0)
  2. Calling SendMessage. In this case you don't really want to throw exceptions because the window procedure will be executed in the UI thread, and if the calling thread is different from the UI thread, the calling thread won't get the exception anyway
  3. Calling the window procedure directly. Exceptions will work fine in this case.
like image 64
user1610015 Avatar answered Sep 22 '22 19:09

user1610015


With C++11, you could handle your situation by manually forwarding any exceptions like this:

#include <exception>
std::exception_ptr windowProcException = nullptr;

LRESULT windowProc(){
  try {
    yourcode();
  catch(...){
    windowProcException = std::current_exception();
  }   
}

You can then rethrow the exception in your mainloop like this:

windowProcException = nullptr;
DispatchMessage();
if (windowProcException)
  std::rethrow_exception(windowProcException);
like image 43
Chronial Avatar answered Sep 23 '22 19:09

Chronial