How to handle std::bad_alloc
exception in this function:
std::string GetString()
{
std::string str;
return str;
}
Since any stl constructor can throw bad_alloc
, we've to do like this:
std::string GetString()
{
try
{
std::string str;
return str;
}
catch(std::bad_alloc&)
{
return ""; // Constructs temporary std::string and returns. Could throw !
}
}
Again catch
block is still not safe.
I just want to make this function exception proof.
Although, (i think) it is not guaranteed by the standard, most (maybe all) std::string
implementations don't allocate memory for an empty/short string (as mentioned by @BoBTFish). So your solution is as "exception proof", as it gets. I'd just suggest, to actually return a default constructed string instead of ""
.
However, the basic question you should ask yourself is if bad_alloc
is something that you expect because you are potentially trying to construct a very big string or if it actually indicates, that your system completely ran out of memory:
If allocation fails, because you try to create a string of a few million characters, then constructing a shorter/empty error string will probably not thorw another exception an can be seen as proper form of error handling.
If it fails, because your program/system ran completely out of memory, you cannot deal with it locally (you e.g. cannot free any other memory) and therefore you probably also should not try to hide that error, because it will certainly come up again shortly after. So while returning an empty or short string would probably still work, I see no reason to catch that exception inside your function in the first place.