Chapter 10: Tackling Those Pesky Errors
Error management can be one of the most frustrating parts of development. It’s hard enough getting everything to work when things go well, but to build really great apps, you need to manage things gracefully when they go wrong. Cocoa provides some tools to make the job easier.
In this chapter, you find the major patterns that Cocoa uses to handle errors that you should use in your own projects. You also discover the major error-handling tools, including assertions, exceptions, and
NSError objects. Because your program may crash in the field, you learn how to get those crash reports from your users, and how to log effectively and efficiently.
There are several useful approaches to handling errors. The first and most obvious is to crash. This isn’t a great solution, but don’t discount it too quickly. I’ve seen a lot of very elaborate code around handling extremely unlikely errors, or errors you won’t be able to recover from anyway. The most common of these is failure to allocate memory. Consider the following code:
NSString *string = [NSString stringWithFormat:@”%d”, 1];
NSArray *array = [NSArray arrayWithObject:string];
It’s conceivable (not really, but let’s pretend) that
stringWithFormat: might fail because Foundation isn’t able to allocate memory. In that case, it returns
nil, and the call to
arrayWithObject: throws an exception for trying to insert
nil into an array, and your app probably crashes. You could ...