thndrkiss
thndrkiss

Reputation: 4595

@throws or NSError which one is appropriate in for objective C api kind of methods

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.

Upvotes: 0

Views: 424

Answers (1)

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

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;
}

Upvotes: 3

Related Questions