I have a class whose ctor makes a driver call, and whose dtor makes the matching terminating/release driver call. Those calls can fail. The problem is naturally with the dtor.
I am naturally aware of the common wisdom of avoiding exceptions in dtors, since, if you throw one during stack unwinding, you get std::terminate
. But - I would rather not just "swallow" such errors and fail to report them - if I can. So, is it legitimate/idiomatic to write code saying:
~MyClass() noexcept(false) {
auto result = something_which_may_fail_but_wont_throw();
if (std::uncaught_exceptions() == 0) {
throw some_exception(result);
}
}
Or is this just baroque and not a good idea?
Note: This class does not have access to the standard output/error streams, nor a log etc.
Under no circumstances should you throw from a c++ destructor.
So its not just 'wisdom' not to throw in a destructor. It will cause your program to crash/exit.
Instead, what I do for this situation, is have a method of the class called something like "Complete".
In the 'Complete' method, you can check for errors codes and throw safely.
You can add a data member (completed) - private - initialized to false, and set true in the Complete () method. And in your destructor, assert its true (so you can catch any cases where you forgot to call Complete).
Throwing from destructors will likely cause grave disorder in your program.