简体   繁体   中英

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:

  • Rethrows the currently handled exception (the same object, not a copy of it)
  • Or, if there is no currently handled exception, calls 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). Thus, std::terminate is called.

The object a is irrelevant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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