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

One Handler, Three Messages

mediumExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3#include <string>
4 
5class ParseError : public std::runtime_error {
6public:
7 explicit ParseError(const std::string& m) : std::runtime_error(m) {}
8};
9 
10class MissingField : public ParseError {
11public:
12 explicit MissingField(const std::string& field) : ParseError("missing field " + field) {}
13};
14 
15class BadNumber : public ParseError {
16public:
17 explicit BadNumber(const std::string& text) : ParseError("bad number " + text) {}
18};
19 
20void 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}
32 
33int 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}

🎯 Your Answer