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 = new char[1000];
delete []c;
And how should you handle exceptions if any?
The reason most people don’t handle a
bad_allocexception 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_allocexception, 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 astd::bad_allocwill fail.Explicitly catching a
bad_allocin 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.