Skip to content
NSError and Out-Parameter Errors
step 1/5

Reading — step 1 of 5

Learn

~1 min readBlocks and Errors

Cocoa's convention: methods that can fail return a primary value (BOOL or object) and take an NSError ** out-parameter.

NSError *err = nil;
NSString *contents = [NSString stringWithContentsOfFile:path
                                                encoding:NSUTF8StringEncoding
                                                   error:&err];
if (!contents) {
    NSLog(@"failed: %@", err.localizedDescription);
} else {
    use(contents);
}

The &err is an out-parameter. If the method fails, it sets *err to an NSError; if it succeeds, error is left alone (often nil).

Convention:

  • Return nil (for object returns) or NO (for BOOL returns) on failure
  • Set *error only if non-NULL and only on failure
  • Don't set error on success

Constructing your own NSError:

NSError *err = [NSError errorWithDomain:@"com.example.MyApp"
                                   code:404
                               userInfo:@{NSLocalizedDescriptionKey: @"not found"}];

Why not just throw? Objective-C does have @throw and @try/@catch, but Cocoa convention reserves them for unrecoverable bugs only (programmer errors). For everything users could reasonably handle, return-value + NSError is the pattern.

Defining a method that takes NSError:

- (NSData *)loadDataFromURL:(NSURL *)url error:(NSError * _Nullable * _Nullable)error;

The _Nullable * _Nullable means "the pointer can be null AND what it points to can be nil." Common idiom — the caller might pass NULL if they don't care about the error.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…