OC进化iOS 开发

解决ios抛出异常信息导致崩溃

2015-11-14  本文已影响1009人  夜千寻墨

在项目中读取本地数据的时候,

[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{

}

可以捕获异常,并且不会崩溃,代码依然执行

上一篇 下一篇

猜你喜欢

热点阅读