事实上,OC是具备异常处理机制的,但是具体情况下不会启用该机制。
ARC默认不是“异常安全”的。如果抛出异常,那么本应该在作用域末尾释放的对象在现在不能自动释放了。如果想生成“异常安全”的代码,需要设置编译标志“-fobjc-arc-exceptions”,并且需要引入额外的代码,在不抛出异常时,也照样执行这段代码。
即使不用ARC,也很难在抛出异常后不会导致内存泄露。
例如:
id resource = [YCResource alloc] init] retain];
if (/*有异常发生*/) {
@throw [NSException exceptionWithName:@"/*异常名称*/" reason@"/*异常原因*/" userInfo:nil];
}
[resource callSomeMethod];
[resource release];
只有在极其罕见的情况下跑出异常,异常抛出之后,无需考虑恢复问题,而且应用程序此时也应该退出。
例如:OC中没有抽象类,所以无法定义抽象方法,此时,如果你想定义一套抽象 的API,那么可以在方法的实现中抛出异常,告诉使用者需要覆写该方法
- (void)absructMethd {
NSString exceptionReason = [NSString stringWithFormat:@"%@ must be overridden", NSStringFromSelector(_cmd)];
@throw [NSException exceptionWithName:NSInternalInnconsistencyException reson:exceptionReason userInfo:nil];
}
在出现"不那么严重的错误"(nonfatal error, 非致命错误)时,Objective-C语言所用的编程范式为: 令方法返回nil/0,或是使用NSError,以表明其中有错误发生。
OC的范式是:另方法返回0/nil,或者使用NSError。
NSError
NSErro使用起来非常灵活,我们使用它告诉调用者发生了什么错误。
//两种初始化方法:其中,domain 不能为空 dict可以为空
- (instancetype)initWithDomain:(NSErrorDomain)domain code:(NSInteger)code userInfo:(nullable NSDictionary *)dict;
+ (instancetype)errorWithDomain:(NSErrorDomain)domain code:(NSInteger)code userInfo:(nullable NSDictionary *)dict;
@property (readonly, copy) NSErrorDomain domain;//错误域
@property (readonly) NSInteger code;//错误代码
@property (readonly, copy) NSDictionary *userInfo;//错误信息
@property (readonly, copy) NSString *localizedDescription;//获取本地化描述
@property (nullable, readonly, copy) NSString *localizedFailureReason;//获取失败原因
@property (nullable, readonly, copy) NSString *localizedRecoverySuggestion;//获取恢复建议
@property (nullable, readonly, copy) NSArray<NSString *> *localizedRecoveryOptions;本地恢复建议
@property (nullable, readonly, strong) id recoveryAttempter;
@property (nullable, readonly, copy) NSString *helpAnchor;
NSError构成
-
Error domain(错误范围)
- 描述错误发生的范围。例如处理URL的子系统,当url解析出现错误,就可以使用NSURLErrorDomain来表示错误范围。
- 错误域主要有四个,对于Carbon框架的Error,归于OSStatus domain(NSOSStatusErrorDomain),对于POSIX error,归于NSPOSIXErrorDomain,而对于我们的iOS开发,一般使用NSCocoaErrorDomain。NSError.h定义了四个domain。
{ // Predefined domain for errors from most AppKit and Foundation APIs. FOUNDATION_EXPORT NSErrorDomain const NSCocoaErrorDomain; // Other predefined domains; value of "code" will correspond to preexisting values in these domains. FOUNDATION_EXPORT NSErrorDomain const NSPOSIXErrorDomain; FOUNDATION_EXPORT NSErrorDomain const NSOSStatusErrorDomain; FOUNDATION_EXPORT NSErrorDomain const NSMachErrorDomain; }
Error code(错误码)
独有的错误代码,用以表明具体发生了何种错误,一般用枚举定义,HTTP请求中可以存储状态码。
Foundation Constants Reference
NSError Codes
NSError codes in the Cocoa error domain.
enum {
NSFileNoSuchFileError = 4,
NSFileLockingError = 255,
NSFileReadUnknownError = 256,
NSFileReadNoPermissionError = 257,
NSFileReadInvalidFileNameError = 258,
NSFileReadCorruptFileError = 259,
NSFileReadNoSuchFileError = 260,
NSFileReadInapplicableStringEncodingError = 261,
NSFileReadUnsupportedSchemeError = 262,
NSFileReadTooLargeError = 263,
NSFileReadUnknownStringEncodingError = 264,
NSFileWriteUnknownError = 512,
NSFileWriteNoPermissionError = 513,
NSFileWriteInvalidFileNameError = 514,
NSFileWriteInapplicableStringEncodingError = 517,
NSFileWriteUnsupportedSchemeError = 518,
NSFileWriteOutOfSpaceError = 640,
NSFileWriteVolumeReadOnlyError = 642m
NSKeyValueValidationError = 1024,
NSFormattingError = 2048,
NSUserCancelledError = 3072,
NSFileErrorMinimum = 0,
NSFileErrorMaximum = 1023,
NSValidationErrorMinimum = 1024,
NSValidationErrorMaximum = 2047,
NSFormattingErrorMinimum = 2048,
NSFormattingErrorMaximum = 2559,
NSPropertyListReadCorruptError = 3840,
NSPropertyListReadUnknownVersionError = 3841,
NSPropertyListReadStreamError = 3842,
NSPropertyListWriteStreamError = 3851,
NSPropertyListErrorMinimum = 3840,
NSPropertyListErrorMaximum = 4095
NSExecutableErrorMinimum = 3584,
NSExecutableNotLoadableError = 3584,
NSExecutableArchitectureMismatchError = 3585,
NSExecutableRuntimeMismatchError = 3586,
NSExecutableLoadError = 3587,
NSExecutableLinkError = 3588,
NSExecutableErrorMaximum = 3839,
}
URL Loading System Error Codes
These values are returned as the error code property of an NSError object with the domain “NSURLErrorDomain”.
typedef enum
{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorDataLengthExceedsMaximum = -1103,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete = -3007
}
-
User info(用户信息)
- 有关错误的额外附加信息,可以是一段本地化描述,也可能是用来存储该错误是由其他错误引起的,最终生成一条完整的错误链。
- 预定义的userinfo键名
NSString *const NSUnderlyingErrorKey;//推荐的标准方式,通用键 NSString *const NSLocalizedDescriptionKey; // 详细描述键 NSString *const NSLocalizedFailureReasonErrorKey; // 失败原因键 NSString *const NSLocalizedRecoverySuggestionErrorKey; //恢复建议键 NSString *const NSLocalizedRecoveryOptionsErrorKey; // 恢复选项键
- 其他键
NSString *const NSRecoveryAttempterErrorKey; NSString *const NSHelpAnchorErrorKey; NSString *const NSStringEncodingErrorKey ; NSString *const NSURLErrorKey; NSString *const NSFilePathErrorKey;
NSError应用场景类型
- 在代理协议中返回NSError错误
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- 在方法中用对象指针来监测错误
- (BOOL)doSomething:(NSError *)error;
/*使用方法*/
NSError *error = nil;
BOOL ret = [slef doSomething:&error];
/**
因为 需要将error 传入后修改其值,然后再返回来,返回来后还要保证己经修改过了。
&error传入是传的地址引用,传入后处理函数直接访问变量的地址,可以修改其值再返回同一个地址, 调用函数就可以知道值是否有修改,即是否有错。
而error传入是传的值引用,值引用传入到程序栈中后其实是把原来的值复制了一份传过去,处理函数可以修改,但无法将改后的值传出函数体。
*/
if (ret) {
// 处理错误
}
要点
只有发生了可使整个应用程序崩溃的严重错误时,才应使用异常。
在错误不那么严重的情况下,可以指派“委托方法”(delegate method)来处理错误,也可以把错误信息放在NSError对象里,经由“输出参数”返回给开发者。