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

An Exception That Carries a Code

mediumExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3#include <string>
4 
5class HttpError : public std::runtime_error {
6 int m_status;
7public:
8 HttpError(int status, const std::string& text)
9 : std::runtime_error(text), m_status(status) {}
10 int status() const { return m_status; }
11};
12 
13void fetch(const std::string& page) {
14 if (page == "/secret") {
15 throw HttpError(403, "forbidden");
16 }
17 if (page == "/old") {
18 throw HttpError(404, "not found");
19 }
20 std::cout << "200 " << page << "\n";
21}
22 
23int main() {
24 std::string pages[] = {"/home", "/secret", "/old"};
25 for (const std::string& page : pages) {
26 try {
27 fetch(page);
28 } catch (const HttpError& e) {
29 std::cout << e.status() << " " << e.what() << "\n";
30 }
31 }
32 return 0;
33}

🎯 Your Answer