A what() Built from a Stored String
A what() Built from a Stored String
std::exception itself stores no message, so a class that inherits from it directly has to keep its own text and return it from what(). Build from scratch:
- ValidationFailure inherits from std::exception: explicit ValidationFailure(const std::string& text) stores the text in a private std::string; const char* what() const noexcept override returns the C string inside it (.c_str())
- RangeFailure inherits from ValidationFailure: RangeFailure(const std::string& field, int limit) passes the text made of the field, above and the limit to the base, and stores the limit for int limit() const
- void checkSpeed(int speed): a speed below 0 throws ValidationFailure("speed is negative"); a speed above 120 throws RangeFailure("speed", 120); otherwise it prints speed ok: and the speed
The tests read speeds from input, one per line, and print range: , what(), (limit , the limit and ) for a RangeFailure, invalid: and what() for any other ValidationFailure, or the ok line. For the first test the input is 60, 130, -5.
Do NOT write a main function.
Expected Output:
speed ok: 60 range: speed above 120 (limit 120) invalid: speed is negative
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...