CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #145

Guards Closing During Unwinding

mediumExceptions

Each function owns a Guard that prints when it is built and when it is destroyed. inner() throws. What is printed?

📄 Code

1#include <iostream>
2#include <stdexcept>
3#include <string>
4 
5struct Guard {
6 std::string name;
7 Guard(const std::string& n) : name(n) { std::cout << "open " << name << "\n"; }
8 ~Guard() { std::cout << "close " << name << "\n"; }
9};
10 
11void inner() {
12 Guard g("inner");
13 throw std::runtime_error("fail");
14}
15 
16void outer() {
17 Guard g("outer");
18 inner();
19 std::cout << "after inner\n";
20}
21 
22int main() {
23 try {
24 outer();
25 } catch (const std::exception& e) {
26 std::cout << "caught " << e.what() << "\n";
27 }
28 return 0;
29}