C++ Exception Handling – How to Ensure Destructors Cannot Throw Exceptions

cexception handling

I know that we can specify the compiler that a function is not throwing an exception by using noexcept specifier but noxecept functions can still throw exceptions . So, how to prevent destructor from throwing an exception ?

Best Answer

If a function is declared as nothrow throws an exception anyway, that is a bug pure and simple.

Given that, to ensure your destructors don't throw any exceptions, there are two paths:

  1. Only call functions that are known not to throw an exception (either because they are declared with nothrow, they are documented not to throw, or they are implemented in a language without exceptions)
  2. Wrap the calls in your destructor that could throw in a try { } catch(...) block.