在項(xiàng)目中讀取本地?cái)?shù)據(jù)的時(shí)候,
[NSKeyedUnarchiverunarchiveObjectWithFile:[selfsavePath]
有一定的概率會(huì)拋出異常,當(dāng)然這個(gè)概率不到萬(wàn)分之一,這里只是舉個(gè)例子。
拋出異常后程序肯定會(huì)崩潰,我也是今天才發(fā)現(xiàn)原來(lái)是有辦法避免這種崩潰的。
看個(gè)例子:常見(jiàn)的越界問(wèn)題
NSString*test =@"test";
unichara;
intindex =6;
a = [testcharacterAtIndex:index];
這樣運(yùn)行直接崩潰
換種方式:
NSString*test =@"test";
unichara;
intindex =6;
@try{
a = [testcharacterAtIndex:index];
}@catch(NSException *exception) {NSLog(@"%@", exception.reason);
}@finally{
NSLog(@"Char at index %d cannot be found", index);
NSLog(@"Max index is: %lu", [testlength]-1);}
使用
@try{
}@catch(NSException *exception) {
}@finally{
}
可以捕獲異常,并且不會(huì)崩潰,代碼依然執(zhí)行