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();
}
}- A. open close caught:body-fail
- B. open close: the program terminates because two exceptions are active at once
- C. open caught:body-fail close
- 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
- What is printed? java public class Main { public static void main(String[] args) { try { level1(); } catch (RuntimeException e) {…
- What is printed? java class MyException extends RuntimeException { MyException(String m) { super(m); } } public class Main { public static…
- What is printed? java public class Main { public static void main(String[] args) { int i = 0; while (true) { try { i++; if (i == 3) break…
- What is printed? java static int f() { int x = 1; try { return x; } finally { x = 2; } } public static void main(String[] a) {…
- What is printed? java static void f() throws Exception { try { throw new RuntimeException("A"); } finally { throw new…
- What is printed? java for (int i = 0; i < 3; i++) { try { if (i == 1) continue; System.out.print(i); } finally { System.out.print("f"); } }