Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is not catching an exception undefined behavior?

Consider the following code:

#include <iostream>

class Widget {
public:
    ~Widget() {
        std::cout << "Destructor Called!";
    }
};

void doStuff() {
    Widget w;
    throw 1;
}

int main() {
    doStuff();
}

Because the exception is not caught in main, the compiler can arrange for the program to call terminate immediately after the throw with ~Widget not called.

Since the standard does not specify whether or not the destructors are called, is this undefined behavior?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: The example is from this CppCon 2015 talk by Fedor Pikus.

Edit: This question asks about the compiler’s freedom for destructor elision, however it is in a special, different situation. The answer to that question does not apply to this question.

>Solution :

Is not catching an exception undefined behavior?

No, it is well-defined that this will result in a call std::terminate (with no UB), albeit whether the stack is unwound before the call is implementation-defined, as per [except.terminate]:

/1 In some situations exception handling is abandoned for less subtle
error handling techniques.

  • […]
  • when the exception handling mechanism cannot find a handler for a thrown exception ([except.handle]), or

/2 In such cases, the function std​::​terminate is called. In the
situation where no matching handler is found, it is
implementation-defined whether or not the stack is unwound before
std​::​terminate is called.
[…] An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to the function std​::​terminate

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading