Objective C 总结(九):Errors

  1. 大多数错误都可以用NSError来进行描述
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

     

  2. 有时候是按引用传递NSError的
    - (BOOL)writeToURL:(NSURL *)aURL
               options:(NSDataWritingOptions)mask
                 error:(NSError **)errorPtr;
        NSError *anyError;
        BOOL success = [receivedData writeToURL:someLocalFileURL
                                        options:0
                                          error:&anyError];
        if (!success) {
            NSLog(@"Write failed with error: %@", anyError);
            // present error to user
        }

     

  3. 生成自定义的错误信息
        NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain";
        NSString *desc = NSLocalizedString(@"Unable to…", @"");
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
     
        NSError *error = [NSError errorWithDomain:domain
                                             code:-101
                                         userInfo:userInfo];

     

  4. Objective-C同样提供了异常处理机制
        @try {
            // do something that might throw an exception
        }
        @catch (NSException *exception) {
            // deal with the exception
        }
        @finally {
            // optional block of clean-up code
            // executed whether or not an exception occurred
        }

    看到有些文档不建议使用异常,有空再研究一下

posted @ 2013-08-09 08:54  万有引用  阅读(315)  评论(0编辑  收藏  举报