Throw an exception in destructor is dangerous and you should never let the exception leave destructors. If there are two exceptions propagating, the program will terminate or yield undefined behavior. Consider the example:
1 |
|
The output will be like:
1 | Throw in ~Bad(). |
Notice that two exception will propagate in the code so that it terminates.
So what should we do if we have to throw an exception in a destructor?
Consider we have a class to handle database connection and has a close method to close the connection. It will throw an exception in close method if close fails.
1 | class DBConnection |
To ensure that clients don’t forget to call close on DBConnection, we have an resource-managing class to handle that:
1 | class DBConn |
But here we allow exception propagate out destructor which is dangerous as we discussed previously. so what’s the solution? We can catch the exception throw in destructor in the same destructor so that it will not propagate out that destructor. But that leads to either terminate the program my ourselves or swallow that exception. That’s not good. What we should do is to provide a close method for clients so that they can handle the exception themselves. But in destructor, we still swallow the exception if clients don’t call close method themselves.
1 | class DBConn |