- 大多数错误都可以用NSError来进行描述
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- 有时候是按引用传递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 }
- 生成自定义的错误信息
NSString *domain = @"com.MyCompany.MyApplication.ErrorDomain"; NSString *desc = NSLocalizedString(@"Unable to…", @""); NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc }; NSError *error = [NSError errorWithDomain:domain code:-101 userInfo:userInfo];
- 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 }
看到有些文档不建议使用异常,有空再研究一下