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?
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 @throw
ing 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 @throw
ing exceptions. To sum up the (quite helpful) commentary on the issue:
error
method demonstrated above or post instances of NSNotification.@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:
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).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With