← Back to Question List
C++ Code Walkthrough #118
An Exception That Carries a Code
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <stdexcept>3#include <string>45class 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};1213void 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}2223int 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}