I'm writing a (C++) application that utilizes a single dialog box.
After setting up a message pump and handler I started wondering how I would go about propagating C++ exceptions to my original code (i.e., the code that calls CreateDialogParam
, for instance).
Here's a skeleton example of what I mean:
BOOL CALLBACK DialogProc(HWND, UINT msg, WPARAM, LPARAM)
{
if(msg == WM_INITDIALOG) //Or some other message
{
/*
Load some critical resource(s) here. For instnace:
const HANDLE someResource = LoadImage(...);
if(someResource == NULL)
{
---> throw std::runtime_error("Exception 1"); <--- The exception handler in WinMain will never see this!
Maybe PostMessage(MY_CUSTOM_ERROR_MSG)?
}
*/
return TRUE;
}
return FALSE;
}
//======================
void RunApp()
{
const HWND dlg = CreateDialog(...); //Using DialogProc
if(dlg == NULL)
{
throw std::runtime_error("Exception 2"); //Ok, WinMain will see this.
}
MSG msg = {};
BOOL result = 0;
while((result = GetMessage(&msg, ...)) != 0)
{
if(result == -1)
{
throw std::runtime_error("Exception 3"); //Ok, WinMain will see this.
}
//Maybe check msg.message == MY_CUSTOM_ERROR_MSG and throw from here?
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//======================
int WINAPI WinMain(...)
{
try
{
RunApp();
//Some other init routines go here as well.
}
catch(const std::exception& e)
{
//log the error
return 1;
}
catch(...)
{
//log the error
return 1;
}
return 0;
}
As you can see, WinMain
will handle "Exception 2" and "3", but not "Exception 1".
My fundemental question is simple; what would be an elegant way to propagate these sorts of errors to the original "calling" code?
I thought of maybe using custom messages and moving the actual throw
-statements out to the message pump (in RunApp()
), but I'm not sure how that would work yet as I have relatively little experience with Windows in general.
Perhaps I'm looking at this situation all wrong. How do you usually bail out when something fatal (i.e., an acquisition of a critical resource fails, and there's no chance for recovery) when you're in the message handler?