Although it won't happen often, there are a couple of cases where my Cocoa application will allocate very large amounts of memory, enough to make me worry about malloc failing. What is the best way to handle this sort of failure in a Cocoa application? I've heard that Exceptions are generally discouraged in this development environment but is this a case where they would be useful?
If you run out of memory there is usually not much you can do short of terminate your app. Even showing a notification could fail because there is not enough memory for that.
The standard in C applications is to write a void xmalloc(size_t size);
function that will check the return value of malloc, and if NULL, print out an error to stderr and then call abort(). That way you just use xmalloc
throughout your code and don't think about it. If you run out of memory, bad luck and your app will die.
If you have an allocation fail because you are out of memory, more likely than not there has been an allocation error in some framework somewhere that has left the app in an undetermined state.
Even if that isn't the case, you can't do anything that'll allocate memory and that leaves you with very few options.
Even freeing memory in an attempt to "fix" the problem isn't going to consistently work, not even to "fix" it by showing a nice error message and exiting cleanly.
You also don't want to try and save data from this state. Or, at least, not without writing all the code necessary to deal with corrupt data on read (because it is quite possible that a failed allocation meant some code somewhere corrupted memory).
Treat allocation failures as fatal, log and exit.
It is extremely uncommon for a correctly written application to run out of memory. More likely, too, when an app runs out of memory, the user's system is going to be paging like hell and, thus, performance had degraded significantly long before the allocation failure.
Your return on investment for focusing on optimizing and reducing memory use will be orders of magnitude greater than trying to recover from an allocation failure.
(Alan's original answer was accurate as well as his edit).