In this recipe, we will learn why throwing exceptions in a destructor is a bad idea, and why class destructors are labeled as noexcept by default. To start, let's look at a simple example:
#include <iostream>#include <stdexcept>class the_answer{public: ~the_answer() { throw std::runtime_error("42"); }};int main(void){ try { the_answer is; } catch (const std::exception &e) { std::cout << "The answer is: " << e.what() << '\n'; }}
When we execute this, we get the following:
In this example, we can see that if we throw an exception from a class destructor, std::terminate() is called. This is because, by default, a class destructor ...