第21条:理解Objective-C错误模型
1.较为严重的情况:@throw 自定义异常
- 抽象基类,只能先继承它写一个子类,然后通过子类调用方法,但是编译器不会识别它是不是抽象基类,所以需要在子类必须覆写的超类方法中抛异常,防止有人创建基类实例:
-(void)mustOverrideMethod{
NSString *reason = [NSString stringWithFormat:@"%@ must be overridden",NSStringFromSelector(_cmd)];
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil];
}
2.不严重的情况:NSError
(1)委托方法
- 例:NSURLConnection的代理
@protocol NSURLConnectionDelegate <NSObject>
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
(2)经由“输出参数”返回给调用者
-(BOOL)doSomething:(NSError **)error{
if(error != nil){
//错误范围-domain,错误码-code,用户信息-userInfo
*error = [NSError errorWithDomain:domain code:code userInfo:userInfo];
NSLog(@"%@",*error);
return NO;
}else{
return YES;
}
}