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 ?
2 Answers
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:
- 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) - Wrap the calls in your destructor that could throw in a
try { } catch(...)
block.
Just mark it noexcept
.
In C++11 and following, your destructor is automatically declared noexcept
unless at least one (base- or member-) subobject's destructor can throw, or you explicitly give a different exception-specification.
And if your function is marked non-throwing, it won't throw, ever, whatever you try.
Instead, it will:
- If your exception-specification is dynamic (
throw()
), callstd::unexpected()
. - If your exception-specification is not dynamic, or
std::unexpected()
throws, callstd::terminate()
to abort the program.
throw
keyword in your destructor, and catch exceptions that called functions throw? Not sure how to "guarantee" this, there are very few guarantees in programming.noexcept
still throw an exception? If a function markednoexcept
throws an exception, the standard requiresstd::terminate
to be called.std::terminate
's requirement is: "A terminate_handler shall terminate execution of the program without returning to the caller."