← Back to Question List
C++ Code Walkthrough #125
One Handler, Three Messages
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <stdexcept>3#include <string>45class ParseError : public std::runtime_error {6public:7 explicit ParseError(const std::string& m) : std::runtime_error(m) {}8};910class MissingField : public ParseError {11public:12 explicit MissingField(const std::string& field) : ParseError("missing field " + field) {}13};1415class BadNumber : public ParseError {16public:17 explicit BadNumber(const std::string& text) : ParseError("bad number " + text) {}18};1920void parse(int line) {21 if (line == 1) {22 throw MissingField("name");23 }24 if (line == 2) {25 throw BadNumber("x7");26 }27 if (line == 3) {28 throw ParseError("line too long");29 }30 std::cout << "line " << line << " parsed\n";31}3233int main() {34 for (int line = 0; line <= 3; line++) {35 try {36 parse(line);37 } catch (const ParseError& e) {38 std::cout << "stopped on line " << line << ": " << e.what() << "\n";39 }40 }41 return 0;42}