I just started reading Effective C++ today and got to the point where the author talks about the operator new.
The book explains very well how you can catch (with various degrees of elegance) the std::bad_alloc exception that the operator new can raise if you run out of memory.
My question is: How often do you check for the case when there isn’t enough memory to instantiate a object, if at all? and why? Is it worth the hassle?
I catch exceptions when I can answer this question:
Most of the time, my answer is, ‘I have no idea. Maybe my caller knows.’ So I don’t catch the exception. Let it bubble up to someone who knows better.
When you catch an exception and let your function proceed running, you’ve said to your program, ‘Never mind. Everything’s fine here.’ When you say that, by golly, everything had better be fine. So, if you’ve run out of memory, then after you’ve handled
std::bad_alloc, you should not be out of memory anymore. You shouldn’t just return an error code from your function, because then the caller has to check explicitly for that error code, and you’re still out of memory. Your handling of that exception should free some memory. Empty some caches, commit some things to disk, etc. But how many of the functions in your program do you really want to be responsible for reducing your program’s memory usage?If you cannot solve the problem that triggered the exception, then do not handle the exception.