Destructors Are noexcept by Default
Since C++11 destructors are implicitly noexcept, so an exception that leaves a destructor calls std::terminate.
Since C++11, a destructor is implicitly noexcept(true), even if you don’t write it. So if an exception leaves a destructor, it doesn’t go to your catch block; the program calls std::terminate.
#include <iostream>
class MyClass {
public:
MyClass() = default;
~MyClass() = default;
};
int main()
{
MyClass a;
// destructors are noexcept(true)
std::cout << "Destructor is noexcept: "
<< std::boolalpha << noexcept (a.~MyClass())
<< std::endl;
return 0;
}
This prints true. Writing throw inside a destructor still compiles (GCC and Clang give a warning), but the program terminates:
#include <iostream>
#include <stdexcept>
class Bad {
public:
~Bad() {
throw std::runtime_error("from destructor");
}
};
int main()
{
try {
Bad b;
} catch (const std::exception& e) {
// never reached, std::terminate is called
std::cout << e.what() << std::endl;
}
}
You can declare ~Bad() noexcept(false) to allow it, but don’t. If a destructor throws while the stack is already unwinding because of another exception, the program terminates anyway. Handle the error inside the destructor instead.