std::stoi
may throw exceptions so it needs to be surrounded by try/catch.
In applications where std::stoi
may be used frequently, it could be useful to have a wrapper.
Is this good practice?
int _stoi(std::string str, int* p_value) {
// wrapping std::stoi because it may throw an exception
try {
*p_value = std::stoi(str);
return 0;
}
catch (const std::invalid_argument& ia) {
//std::cerr << "Invalid argument: " << ia.what() << std::endl;
return -1;
}
catch (const std::out_of_range& oor) {
//std::cerr << "Out of Range error: " << oor.what() << std::endl;
return -2;
}
catch (const std::exception& e)
{
//std::cerr << "Undefined error: " << e.what() << std::endl;
return -3;
}
}
std::stoi
is specified as if it was a wrapper aroundstd::strtol
that reports errors by throwing exceptions. So the way to not deal with exceptions is not to add another wrapper, but to unwrap and usestd::strtol
directly, or perhaps through a wrapper that provides the desired (non-exception) interface. \$\endgroup\$std::from_chars
. \$\endgroup\$-fno-exceptions
impossible, which defeats the purpose of your code. \$\endgroup\$