Search code examples
objective-cexceptionerror-handlingnsassert

Practice for handling errors in Objective C client code


I’ve seen Objective C code using a collection of practices, raging from passing a pointer of NSError for execution finish status - to using ‎NSAssert - to implementing @throw - to relaying on delegate for status code returned in the callback - to the old c method of returning a boolean/int indicating with 1 being success and co.

I can’t identify a consistent pattern for how should I be handling errors happening in my app running on client devices. For ex, what would you recommend handling for the following cases:

  • Client attempt to access a network resource, network resource timed out / returned 500?
  • Unexpected state that should have not even happened reached in logical code section?
  • Attempt to write to disk failed? (Out of disk space, not permission and code)

Coming from Java, server side practices exceptions the weapon of choice, using Objective C and C is seems that exceptions exist but are not encouraged. NSAssert seems harsh, as it will crash the application, which in most cases is not the optimal solution. So, I’d appreciate a Best practices advice.


Solution

  • Exceptions are used to indicate programmer error and/or non-recoverable errors only. Exceptions should not be used for flow control. NSAssert is more of a development tool. Use NSError for recoverable, user addressable (or caused) errors.

    https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorHandling/ErrorHandling.html