The destructor will not be launched if an exception occurs in the constructor.
It will be triggered if necessary (if the exception is handled somewhere) if the exception is raised in another method, for example, in your example. But as the program ends, the call to the destructor is not needed here, and the behavior depends on the compiler ...
The idea of RAII is that the constructor allocates ressources, and the destructor frees them. If an exception occurs in the constructor, there is no easy way to find out which resources were allocated and which were not (this depends on the exact place in the constructor where the exception occurred). You should also remember that if the constructor fails, the only way to tell it to cause it to throw an exception and the allocated memory is freed (stack unwinding or allocated heap memory) as if it had never been allocated.
The solution is obvious: if any exception can occur inside the constructor, you should catch it and release the allocated resources if necessary. In fact, this may be some kind of duplicate code with a destructor, but this is not a big problem.
In the destructor, you should not raise exceptions, as this can lead to big trouble with erasing the stack.
In any other method, use exceptions as you like, but remember to handle them somewhere. An unhandled exception can be worse than an exception in general. I know some programs that do not handle exceptions for some minor errors ... and crash due to errors that should give a warning.
kriss
source share