Constructor can throw an exception.
The C ++ Standard specifies that the Destructor cannot or should not throw an exception.
If the object encounters an exception during running, the C ++ Exception Handling model has the responsibility to clear invalid objects due to exceptions (that is, the objects exceed their original scope ), and release the original resources of the object. This is to call the destructor of these objects to release the resource. Therefore, in this sense, the Destructor has become part of exception handling.
In the above discussion, the C ++ Exception Handling model has a premise assumption that the Destructor should not throw any more exceptions. Imagine that if an exception occurs to an object, the exception handling module now has the responsibility to release the resource of this object and call the object's destructor to maintain data consistency of the system object and avoid resource leakage, but now, if there is another exception in the structure analysis process, who will ensure the resource release of this object? Who will handle this new exception? Don't forget that the previous exception has not been processed yet, so it is in conflict or infinite recursive nesting.
What should I do if no exception occurs in the Destructor?
In fact, there is still a good solution. That is, the exception is completely encapsulated inside the destructor, and the exception is never thrown out of the function. This is a very simple and effective method.
~ Classname ()
{
Try {
Do_something ();
}
Catch () {// nothing can be done here, but the exception thrown by the Catch Block program will not be thrown out of the destructor.
}
}
3.3 Summary of exceptions thrown in destructor
1) The execution of destructor in C ++ should not throw an exception;
2) if an exception is thrown in the destructor, your system will become very dangerous. It may not happen for a long time; however, your system may sometimes crash inexplicably and quit without any signs. It's hard to find out where the problem is;
3) when some (even a little) Exceptions occur in a destructor, then, we must completely encapsulate this possible exception in the destructor, and never let it throw out of the function (this is a perfect trick! Haha !);
4) be sure to remember the above summary. The unexpected crash caused by exceptions thrown in the Destructor is a fatal internal injury to many systems!
Constructor and destructor throw an exception