Exceptions when allocating memory
I've just learnt than you could throw or handle exceptions if memory allocation wasn't successful. But on here, I haven't seen many people handle exceptions when using new
operator
.
For example: Isn't the following likely to fail at any point in program?
char* c = 开发者_Go百科new char[1000];
delete []c;
And how should you handle exceptions if any?
new throws the exception std::bad_alloc you should catch it by using, try-catch block:
try
{
char* c = new char[1000];
}
catch(std::bad_alloc &except)
{
}
The basic guideline I follow with exceptions is:
Handle the exception when you can and if you can recover from the exception, take the necessary actions to recover from it, if you can't then you just terminate the application/program by logging appropriate diagnostic.
In cases of an memory allocation failure, an application/program cannot usually continue or recover, So exit by logging some diagnostic message or just let it crash by allowing the exception to propagate upwards.
The reason most people don't handle a bad_alloc
exception explicitly is because most of the time there isn't a lot most user applications can do to recover from low memory conditions so letting the exception propogate outwards is the most sensible thing to do. You should only explicitly catch an exception if there is a sensible recovery action that you can perform.
In some cases it can make sense to catch a std::bad_alloc
exception, for example if the program can attempt an alternative approach when allocating a large block of memory fails. This only applies in some systems; in a system that overcommits memory, speculatively allocating a large block of memory and expecting a std::bad_alloc
will fail.
Explicitly catching a bad_alloc
in order to do clean up is usually a sign that resources aren't being managed by appropriate instances of RAII-style classes that should doing the correct clean up in a destructor ensuring that it happens whenever a scope is left, whether by any exception or in some other way.
精彩评论