Parse an Age Without Throwing
Parse an Age Without Throwing
Not every error needs an exception. Write tryParseAge(const std::string& text, int& ageOut), a function marked noexcept that reports success with a bool instead of throwing: convert text with std::stoi; if the conversion throws (it uses std::invalid_argument and std::out_of_range), or the number is below 0 or above 150, return false and leave ageOut alone; otherwise store the number in ageOut and return true. Because the function promises noexcept, it must catch everything std::stoi can throw inside itself; an exception escaping a noexcept function ends the program. Compare this with a throwing version: the caller of a throwing parseAge needs a try, while the caller here only tests the bool.
The tests read one line at a time and print age: and the value, or invalid: and the text. For the input lines 42, abc and 7 the output is shown in Expected Output.
Do NOT write a main function.
Expected Output:
age: 42 invalid: abc age: 7
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...