程序中寫了如下代碼, 就會(huì)立即崩潰
NSArray *arr = @[@"A"];
arr[3];
并會(huì)報(bào)錯(cuò)
-[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 0]
崩潰導(dǎo)致用戶不能使用App的其他功能, 是最壞的情況, 使用異常的捕捉就可以避免程序的直接崩潰
NSLog(@"111111111");
@try {
NSArray *arr = @[@"A"];
arr[3];
NSLog(@"222222");
}
@catch (NSException *exception) {
NSLog(@"%@",exception);
NSLog(@"3333333");
}
@finally {
NSLog(@"4444444");
}
NSLog(@"555555");
使用捕捉后打印的信息是:
111111111
*** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 0]
3333333
4444444
555555
可以看到, 即使是try發(fā)生了崩潰, try塊停止執(zhí)行, 但是其他塊還是會(huì)執(zhí)行.
如果要捕捉發(fā)生的異常進(jìn)行保存和上傳后臺(tái)服務(wù)器, 那么可以通過
NSException
中的方法驚醒捕捉
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// 設(shè)置捕捉異常的回調(diào)
NSSetUncaughtExceptionHandler(handleException);
return YES;
}
/**
* 攔截異常
*
* @param ex 發(fā)送的異常會(huì)傳遞到函數(shù)中
*/
void handleException(NSException *ex){
NSMutableDictionary* info = [NSMutableDictionary new];
info[@"callStackSymbols"] = [exception callStackSymbols]; // 調(diào)用棧信息(錯(cuò)誤來源于哪個(gè)函數(shù))
info[@"name"] = [exception name]; // 異常的名字
info[@"reason"] = [exception reason]; // 異常的描述(報(bào)錯(cuò)理由)
[info writeToFile:@"xxxxxxx" atomically:YES];
}
如上發(fā)生的異常就會(huì)傳入handleException
函數(shù)中, 程序猿就可以對(duì)發(fā)生的異常進(jìn)行寫入本地文件的操作. 等下次用戶啟動(dòng)應(yīng)用,傳給后臺(tái).