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

Three Tries and Then Give Up

hardExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3 
4int attempts = 0;
5 
6int connect() {
7 attempts++;
8 std::cout << "attempt " << attempts << "\n";
9 if (attempts < 4) {
10 throw std::runtime_error("timeout");
11 }
12 return attempts * 10;
13}
14 
15int main() {
16 bool connected = false;
17 for (int tries = 1; tries <= 3 && !connected; tries++) {
18 try {
19 int handle = connect();
20 std::cout << "connected with handle " << handle << "\n";
21 connected = true;
22 } catch (const std::runtime_error& e) {
23 std::cout << "try " << tries << " failed: " << e.what() << "\n";
24 }
25 }
26 if (!connected) {
27 std::cout << "giving up after " << attempts << " attempts\n";
28 }
29 return 0;
30}

🎯 Your Answer