Chapter 8: 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 learn the major patterns that Cocoa uses to handle errors that you should use in your own projects. You also learn 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.

Error Handling Patterns

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 is 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 (and ...

Get iOS 5 Programming Pushing the Limits: Developing Extraordinary Mobile Apps for Apple iPhone, iPad, and iPod Touch now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.