可以从_CrtSetReportHook抛出异常吗? [英] Can I throw an exception from _CrtSetReportHook?

查看:255
本文介绍了可以从_CrtSetReportHook抛出异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个C ++程序中,我想将这些报告转换为异常。使用C ++ throw语句是一种合理的方法,或者我只是重定向到stderr?

解决方案

不,你不能从你的钩子中引发C ++异常。



它可能会在某些时间工作 - 但是一般来说 - 当钩子被调用时,CRT处于不确定的状态,可能不再能够抛出或处理异常。当CRT出现故障时抛出异常,是类似的情况,即由于异常而在堆栈展开期间调用的对象的析构函数抛出异常。此外,CRT的深度不是投掷C ++异常的适当场所,这样做可能会使运行时处于不良状态 - 如果还没有的话!



你应该做的是:

  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\\\
,szMsg);

/ *提升中止信号* /
raise(SIGABRT);

/ *我们通常不会在这里,但是可能会忽略
SIGABRT。所以退出程序。 * /
_exit(3);
}


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?

解决方案

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

这篇关于可以从_CrtSetReportHook抛出异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆