4 ms·
> Well then the C++ standard people are doing it wrong, because something as expected-to-fail as converting a string to a number throws an exception. I wouldn'
by Suncho 9y ago
> Well then the C++ standard people are doing it wrong, because something as expected-to-fail as converting a string to a number throws an exception.
I wouldn't say that they are doing it wrong. They throw an exception because they don't want to make assumptions about how you would want to handle the error.
What would you prefer the std::stoi() function to do?
- IshKebab 9y agoEither allow you to specify a default value on failure, or take an optional `bool* success = nullptr` parameter to indicate failure. Or in C++17, return `std::optional<int>`.
- Suncho 9y agoThen std::atoi() would be making the assumption that you want to handle the error as soon as the function call returns. Furthermore, if you don't check the "success" flag, then your function would fail silently. The exception ensures that something reasonable happens (program termination) when the client does nothing to handle the error. Exceptions are cleaner.