Looking at some old code we have lots of things like the following:
// This is dumb
string do_something(int in)
{
stringstream out;
try
{
out << std::fixed << in;
}
catch(std::exception &e)
{
out << e.what();
}
return out.str();
}
// Can't we just do this? Can this ever fail?
string do_something_better(int in)
{
stringstream out;
out << std::fixed << in;
return out.str();
}
When a stringstream reads a primitive can it ever throw an exception? What about when reading a string?
Summarizing a few answers
By default, streams don’t throw exceptions. They can if they are enabled.
According to the
Apache C++ Standard Library User’s Guide
So it seems like the safest way to do this would be
This is overkill though because according to Handling bad_alloc if creating the stream fails, there are bigger problems to worry about, and the program is probably going to exit. So assuming it gets past creating the stream, it’s possible but extremely unlikely that the badbit gets set. (Stream gets allocated with memory < sizeof(int)).
It’s also unlikely that the failbit gets set (not sure of a use case for reading off the stack other than a corrupt stack). So the following code is sufficient, as recovering from a stream error at this point is unlikley.