在项目中读取本地数据的时候,
[NSKeyedUnarchiverunarchiveObjectWithFile:[selfsavePath]
有一定的概率会抛出异常,当然这个概率不到万分之一,这里只是举个例子。
抛出异常后程序肯定会崩溃,我也是今天才发现原来是有办法避免这种崩溃的。
看个例子:常见的越界问题
NSString*test =@"test";
unichara;
intindex =6;
a = [testcharacterAtIndex:index];
这样运行直接崩溃
换种方式:
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{
}
可以捕获异常,并且不会崩溃,代码依然执行