CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #123

The Catch Runs Before main Cleans Up

mediumExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3 
4class Session {
5public:
6 Session() { std::cout << "session begins\n"; }
7 ~Session() { std::cout << "session ends\n"; }
8};
9 
10void save(bool ok) {
11 if (!ok) {
12 throw std::runtime_error("save failed");
13 }
14 std::cout << "saved\n";
15}
16 
17int main() {
18 Session session;
19 try {
20 save(true);
21 save(false);
22 save(true);
23 } catch (const std::runtime_error& e) {
24 std::cout << "caught: " << e.what() << "\n";
25 }
26 std::cout << "cleaning up\n";
27 return 0;
28}

🎯 Your Answer