Do you always must check for bad_alloc whenever dynamically allocating memory?

93 Views Asked by At

If new cannot find enough memory, it throws an exception. Do I absolutely always need to check for that? I never did that and had no issues, but now I've read you should do that. Or only in certain cases?

try
{
    pPos = new Vector2D(5,1);
}
catch(bad_alloc)
{
    // NO MEMORY!
}
1

There are 1 best solutions below

0
On

There's nothing special about bad_alloc, you can catch it or not as you would any other exception. It is unusual to catch it. You would only do that if you had some way to recover from the out-of-memory condition. But I think programs that are designed to deal with out-of-memory errors more commonly use the nothrow version of new instead:

pPos = new (std::nothrow) Vector2D(5,1);
if (!pPos) {
    // NO MEMORY!
}