0

Which one is the most preferred objective C exception handling ? NSError pointer which give the pointer with message details within it or @throws which forces the caller to handle exception and show some graceful message. Thanks.

and alos please let me know which one is memory efficient.

thndrkiss
  • 4,515
  • 8
  • 57
  • 96
  • 1
    You are confusing exception handling with error handling. There's a reason Apple made two different classes - `NSException` and `NSError`. –  Jul 09 '13 at 21:38
  • 1
    In short, don't throw an exception unless some internal inconsistency, assertion failure, etc. happens. If the web API returned an error, the user entered an invalid password or your mother-in-law has stomach ache, report it back to the caller function using an `NSError`. –  Jul 09 '13 at 21:40

1 Answers1

3

Unlike Java, in Objective-C exceptions are just used to handle unrecoverable states. This means that for example, you don't catch EXC_BAD_ACCESS, rather you debug your application and correct the problem.

The Objective-C equivalent of Java exceptions is NEError and the null pointer pattern. For example if a formatter fails to format a string to a number because the string does not represent a number, it returns nil. There is also a method to format the number that takes a NSError double pointer to return the error description.

So to handle errors you typically implement a method like this:

- (id) object : (out NSError**) error
{
    BOOL ok= ... 
    if(!ok)
    {
        if(error)
            *error= ...
        return nil;
    }
    return someObject;
}
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187