Can I throw an exception from _CrtSetReportHook?
Assuming I'm in a C++ program, I want to convert these reports to exceptions. I开发者_运维问答s using a C++ throw statement a reasonable way to do it, or am I stuck just redirecting to stderr?
No, you can not throw C++ exceptions from your hook.
It may work some of the time - but in general - when the hook is invoked the CRT is in an indeterminate state and may no longer be able to throw or handle exceptions. Throwing an exception when the CRT is in trouble, is a similar scenario to throwing an exception from the destructor of an object, that has been called during stack unwinding, due to an exception. Also, the depths of the CRT is not an appropriate place to throw C++ exceptions, doing so might leave the runtime in a bad state - if it wasn't already!
What you should do is the following:
int no_dialog_box_but_act_as_if_it_had_appeared_and_abort_was_clicked (int /* nRptType */,
char *szMsg,
int * /* retVal */)
{
fprintf (stderr, "CRT: %s\n", szMsg);
/* raise abort signal */
raise (SIGABRT);
/* We usually won't get here, but it's possible that
SIGABRT was ignored. So exit the program anyway. */
_exit (3);
}
精彩评论