Hello there, today I want to share with you another great tip from Scott Meyers' book Efficient C++. The tip is as follows:
Prevent exceptions from leaving destructors
Even better, if you can avoid using exceptions in destructors, do so. This is because C++ does not like destructors that emit exceptions.
Ok, that is great, but what if you absolutely need to have an operation in your destructor that may throw an exception? What can you do?
If there is a throw, you can either:
- Terminate the program
For example:
Point::~Point(){
try{myOperation();}
catch(...){
//make a log entry
//abort operation
std::abort();
}
}
- Swallow the exception For example
Point::~Point(){
try{myOperation();}
catch(...){
//make a log entry
}
}
Neither of these two options are ideal. You can't just ignore an scenerio when an operation may throw an exception.
Scott Meyers provides the following tip:
If an operation may fail by throwing an exception and there may be a need to handle the exception, the exception has to come from some non-destructor function.
The reason for this is that destructors that emit exceptions are dangerous, running the risk of premature program termination or undefined behavior.
So, these are the takeaways:
- Destructors should never emit exceptions
- Make sure that another non-destructive method takes care of handling any exceptions throw.
If you want to get more tips, sign up to my newsletter below.