Back to questions
JuniorTheoryCommon
What happens when this program runs?
#include <iostream>
#include <stdexcept>
struct Logger {
~Logger() { throw std::runtime_error("flush failed"); }
};
int main() {
try { Logger log; }
catch (const std::exception&) { std::cout << "caught"; }
}The program calls std::terminate: the destructor is noexcept
- Expecting
caught: a destructor isnoexceptby default, so an exception leaving it callsstd::terminate, and no handler runs. - Expecting a compile error: a
throwin a destructor builds, and GCC and Clang only warn about it.
- How can
Loggerreport a failed flush without throwing from its destructor? - What changes if the destructor catches its own exception inside a
tryblock?