简体   繁体   English

引发导致析构函数被调用的异常导致程序崩溃

[英]Throwing an exception which causes a destructor to be called crashes the program

Consider this small snippet of code, which is actually part of a larger codebase: 考虑一下这小段代码,它实际上是较大代码库的一部分:

class A
{
public:
    A()
    {
        std::cout << "A" << std::endl;
    }

    ~A()
    {
        std::cout << "~A" << std::endl;
    }
};

void f()
{
    A a;
    throw;
}

void g()
{
    try
    {
        f();
    }
    catch(...)
    {
        std::cout << "Caught" << std::endl;
    }
}

For my particular case, the output turns out to be 对于我的特殊情况,输出结果是

A
~A

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

It seems that rather than the exception being caught, the program is just terminated. 似乎终止了程序,而不是捕获异常。 However, if I remove A's constructor, the exception does get caught. 不过,如果我删除的构造,除了被逮住。

Without closely analyzing the code, is it possible to know what causes this sort of behaviour? 如果不仔细分析代码,是否有可能知道导致此类行为的原因?

A throw-expression with no operand, as in your code: 没有操作数的throw-expression ,如您的代码所示:

  • Rethrows the currently handled exception (the same object, not a copy of it) 重新抛出当前处理的异常(同一对象,而不是其副本)
  • Or, if there is no currently handled exception, calls std::terminate . 或者,如果当前没有处理的异常,则调用std::terminate

I am assuming f() is not being called while an exception is being handled (I imagine you're calling it directly from main or something). 我假设在处理异常时调用f() (我想您是直接从main或其他对象调用它)。 Thus, std::terminate is called. 因此,将调用std::terminate

The object a is irrelevant. 对象a不相关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM