Can I throw an exception from _CrtSetReportHook?

蹲街弑〆低调 提交于 2019-12-11 00:52:23

问题


Assuming I'm in a C++ program, I want to convert these reports to exceptions. Is using a C++ throw statement a reasonable way to do it, or am I stuck just redirecting to stderr?


回答1:


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);
}


来源:https://stackoverflow.com/questions/6962741/can-i-throw-an-exception-from-crtsetreporthook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!