ProgrammingVery hardProduct-company placement · C++
What is printed?
What is printed?
struct M { M() { throw 1; } };
struct S {
M m;
S() try : m() { }
catch (int) { cout << "S"; }
};
int main() {
try { S s; } catch (int) { cout << "main"; }
}- A. S
- B. Smain
- C. main
- D. Compile-time error: try cannot wrap an initializer list
Correct answer: B. Smain
A function-try-block can catch exceptions from member initialisers, but for a constructor the handler cannot swallow them: reaching its end automatically rethrows, because the object could not be constructed.
More OOP with C++ and Java questions
- What is printed? cpp void f() noexcept { } void g() { } int main() { cout << noexcept(f()) << noexcept(g()); }
- What happens when this is compiled? cpp int main() { try { throw 1; } catch (...) { cout << "any"; } catch (int) { cout << "int"; } }
- What is printed? cpp int main() { try { throw runtimeerror("disk full"); } catch (const exception& e) { cout << e.what(); } }
- What is printed? cpp struct E { }; int main() { try { throw new E(); } catch (E&) { cout << "ref"; } catch (E) { cout << "ptr"; } }
- What is printed? cpp int main() { try { throw 1; } catch (long) { cout << "L"; } catch (double) { cout << "D"; } catch (...) { cout <<…
- What is printed? cpp struct E { }; struct F : private E { }; int main() { try { throw F(); } catch (E&) { cout << "E"; } catch (...) {…