NSException(异常处理) 与 NSError(错误处理)
在实际的开发过程中总是会遇到一些错误,除崩溃以外,都是使用 NSError 来表示逻辑上的错误。系统层面的错误,或者说崩溃信息怎么表示?
NSException
由于每次程序崩溃的时候,最终会到达main入口,并且会显示当前调用栈信息,里面就涉及到一个类 NSException(最后表示信息是程序由 NSException 终止的,并且附带一些错误信息), 所以,由此引入程序崩溃的错误。
(
...
17 UIKit 0x000000010bef208f -[UIApplication _run] + 468
18 UIKit 0x000000010bef8134 UIApplicationMain + 159
19 CrashTest 0x000000010af6b9c0 main + 112
20 libdyld.dylib 0x000000010e93e65d start + 1
21 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
从文档中可以看出主要包含3个点
name: NSExceptionName
异常类型名称
reason:NSString
异常原因,类似于 reason: '-[NSNull rangeOfCharacterFromSet:]:
userInfo:NSDictionary
用户信息,用户可以自行创建相关信息
异常捕获
在之前有用过try-catch来捕获异常
@try {
<#Code that can potentially throw an exception#>
} @catch (NSException *exception) {
<#Handle an exception thrown in the @try block#>
} @finally {
<#Code that gets executed whether or not an exception is thrown#>
}
由于try-catch会造成内存管理上的一些问题,还有block使用效率的问题,并不推荐使用,但是有些其中有个问题,并不是所有崩溃都能catch到,所以catch捕获异常有限
自行创建 NSException,可以新增自己的异常类型并处理
@try {
NSException *exception = [NSException exceptionWithName:@"SDK_ERROR" reason:@"can not be nil" userInfo:nil];
@throw exception;
} @catch (NSException *exception) {
NSLog(@"%@", exception.reason);
} @finally {
}
还有一种方式:NSSetUncaughtExceptionHandler,可以统一处理异常信息,他可以捕获到所有异常情况,也可以在这里生成异常报告
void uncaughtExceptionHandler(NSException *exception)
{
NSString *resason = [exception reason];
NSString *name = [exception name];
NSLog(@"%@", resason);
NSLog(@"%@", name);
}
void initCreashReport(){
NSSetUncaughtExceptionHandler(& uncaughtExceptionHandler);
}
int main(int argc, char * argv[]) {
@autoreleasepool {
initCreashReport();
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
NSError
这个比较熟悉,主要有以下几点
- domain
- code
- userinfo
NSError *error;
BOOL success = [writer writeTo:filePath withData:data error:&error];
if (success == NO) {
}
通过返回 NSError 来判断错误类型,并不会终止程序
网友评论