cleaning up after an exception
c++, exception
Solution
If there is an exception in do function, what would happen?
If you have any handler, it will be handled.
Is destructor of myclass called?
Yes, definitely. The standard quotes this::
An object of any storage duration whose initialization or destruction is terminated by an exception will have destructors executed for all of its fully constructed subobjects (excluding the variant members of a union-like class), that is, for subobjects for which the principal constructor (12.6.2) has completed execution and the destructor has not yet begun execution. Similarly, if the non-delegating constructor for an object has completed execution and a delegating constructor for that object exits with an exception, the object’s destructor will be invoked. If the object was allocated in a new-expression, the matching deallocation function (3.7.4.2, 5.3.4, 12.5), if any, is called to free the storage occupied by the object.
This whole process is known as "stack unwinding":
The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.” If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1).
C++11 15.5.1 The std::terminate() function [except.terminate]
2 … 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.
Problem
I have a code such as this: ``` class myclass { myclass() { // doing some init here } ~myclass() { // doing some important clean up here } void Do() { // doing some work which may throw exception } } ``` and I am using this class in this way: ``` MyFunction() { myclass mc; mc.do(); } ``` My question is : If there is an exception in do function, what would happen? Is destructor of myclass called? If no, what is the best way to handle this type of situations? Assume that I don't have the source code and I am sure about what is happening in destructor.