CJCoding With Joseph
15free / daySign inCreate account

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.

Hints4 available
Topics:
Exceptions
📥 Auto-Input:
42\nabc\n7\n
This input is automatically fed to your program's stdin
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.