Chapter 10. Error and exception handling

 

This chapter covers

  • Dealing with NSError
  • Creating your own NSError objects
  • When and when not to use exceptions

Things go wrong. That’s no surprise. And things go wrong in the software you build. Maybe the server that hosts the API you want to talk to isn’t reachable, or the XML file you need to parse is corrupt, or the file you want to open doesn’t exist. You need to prepare for such cases and handle them gracefully, which means not crashing and giving the user an appropriate message.

Cocoa Touch and Objective-C offer two ways of dealing with errors: NSError and exceptions. NSError is the preferred and advisable way to deal with expected errors (like an unreachable host). Exceptions are meant to report and handle programming errors during development and shouldn’t be used to handle and report errors to the user at runtime. That makes the purpose of exceptions in Objective-C quite different from other languages, such as Java, where they’re used frequently.

In this chapter we look mainly at NSError and at some real-life use cases for exceptions.

10.1. NSError—handling errors the Cocoa way

In Cocoa and Cocoa Touch, nearly all methods that could possibly fail for reasons you as a developer can’t control take a pointer to an NSError pointer as their last parameter. Why a pointer to a pointer? Because that way the called method can create an instance of NSError and you can access it afterwards through your NSError pointer.

10.2. Creating NSError objects

10.3. Exceptions

10.4. Summary