ProgrammingVery hardIBM · Deloitte pattern

What is printed?

What is printed?
struct Logger {
    Logger() { cout << "open "; }
    ~Logger() noexcept(false) { cout << "close "; throw runtime_error("dtor-fail"); }
};
int main() {
    try {
        Logger l;
        throw runtime_error("body-fail");
    } catch (const exception &e) {
        cout << "caught:" << e.what();
    }
}
  1. A. open close caught:body-fail
  2. B. open close: the program terminates because two exceptions are active at once
  3. C. open caught:body-fail close
  4. D. open close caught:dtor-fail

Correct answer: B. open close: the program terminates because two exceptions are active at once

While the body-fail exception is already propagating (unwinding the stack), l's destructor runs and ALSO throws; having two simultaneously-active exceptions during unwinding is fatal in C++ and calls std::terminate, so the program aborts after printing "open close " rather than reaching any catch block.

More OOP with C++ and Java questions

Exams that ask this topic