tags:

views:

60

answers:

1

Hi,

Google Coding Standard for Objective C says we should not throw exceptions, what are the alternatives to @throw then?

+6  A: 

One possibility is to deliver extended exception information via NSError:

- (BOOL) doSomethingWhichCanFailWithError: (NSError**)aLocation {
    ...
    if( didFail ) {

        if( aLocation ) {

            *aLocation = [NSError errorWithDomain: kMyErrorDomain code: myErrorCode userInfo: nil];
        }
    }

    return !didFail;
}

The caller can test if the call succeeded by inspecting the result value. If more information is required in case of an error, it can supply a location, where the method can store additional information into:

NSError* error = nil;

if( ![instance doSomethingWhichCanFailWithError: &error] ) {

    NSString* domain = [error domain];

    if( [kMyErrorDomain isEqual: domain] ) {

         switch( [error code] ) {
         case ...: ...
         default: ...
         }
    }
}
Dirk
+1 This is the Apple recommended pattern. Personally I like exceptions and I use them where appropriate but you can't allow exceptions to propagate outside your own code because whatever calls your code may not support exceptions.
JeremyP