Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning errors in objective-c

Im newish to objective-c and am starting to wonder what is the common/standard/proper way for handling and catching errors?

It seems like it might be possible to use NSError to do this, is that a good idea or a hijack of cocoa?

like image 808
Jay Avatar asked Oct 01 '09 11:10

Jay


1 Answers

I'm pretty sure that's what the NSError class is there to do - give details about errors. The most common pattern you'll see is a method that takes a pointer to an NSError object, as in:

- (id)doSomethingWithArgument:(id)arg error:(NSError **)error

The method returns some value (or possibly nil) for the result of doing something, but if the call failed will place an NSError object at the pointer passed with details about the failure. Your documentation is responsible for specifying what gets returned if the method does encounter an error.

The other method that comes to mind is the @throw-@catch block; however, in Objective-C @throwing an exception can be rather computationally expensive, and it's usually only recommended to do so in truly exceptional situations.

Edit: wow, turns out a lot of people have really strong opinions about @throwing exceptions. To sum up the (quite helpful) commentary on the issue:

  • Throwing exceptions should most often deal with programmer error (situations that should never happen, and the like); exceptions should not be used for ordinary error handling. Instead, use the error method demonstrated above or post instances of NSNotification.
  • If you do wind up making extensive use of @throw/@catch blocks, be very careful about the logic surrounding them. Objective-C provides a lot of ways to detach methods to run in other threads, or delay execution, etc. Be very careful to account for all those possibilities when you write your code.

Finally, another very valid point:

  • If you do use the error object passed to a method, the return value should indicate it. Don't try to do both (return a partially valid object and set the error object).
like image 147
Tim Avatar answered Oct 20 '22 16:10

Tim