简体   繁体   中英

Stack unwinding with (un)caught exceptions

stack unwinding

In the stack unwinding section there are the two following paragraphs:-

Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of a try block, at which point the parameters of all associated catch blocks are compared, in order of appearance, with the type of the exception object to find a match (see try-catch for details on this process). If no match is found, the control flow continues to unwind the stack until the next try block, and so on. If a match is found, the control flow jumps to the matching catch block. As the control flow moves up the call stack, destructors are invoked for all objects with automatic storage duration that are constructed, but not yet destroyed

Then we have

If an exception is thrown and not caught, including exceptions that escape the initial function of std::thread, the main function, and the constructor or destructor of any static or thread-local objects, then std::terminate is called.It is implementation-defined whether any stack unwinding takes place for uncaught exceptions.

Now I'm a bit confused, at first it says as we move up the stack looking for a try with a matching catch, the destructors are called and then it says if the exception is not caught the destructors are not guaranteed to be called. Which is it? Does the runtime keep track of the destructors that would potentially be called until it finally finds a matching catch and only then it calls them in reverse order of construction? Moreover, are the destructors called before the catch gets executed?

You seem to be under the impression that the destructors are called while searching for a matching catch() . That does not have to be the case.

Destructors from the current location in the program to the matching catch() end up getting called, but that does not need to start happening until the catch is found.

The second block just states that of no catch is found, then the program is allowed to immediately terminate as soon as it makes that determination.

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