異常處理
- 在日常開(kāi)發(fā)中烘跺,我們經(jīng)常會(huì)自定義很多東西,這些代碼調(diào)用過(guò)程中需要傳遞必要的參數(shù)
- 如果參數(shù)傳遞不正常脂崔,那么會(huì)引起程序崩潰等后果
如果這個(gè)參數(shù)必須傳遞正確,那么我們可以對(duì)傳遞不正確的參數(shù)進(jìn)行異常的拋出
- 前提條件是:必須傳遞正確
// 第一種方式:
@throw [NSException exceptionWithName:@"代碼出錯(cuò)" reason:@"出錯(cuò)原因" userInfo:nil];
// 第二種方式:
[NSException raise:@"代碼出錯(cuò)" format:@"出錯(cuò)原因"];
- 上面這兩種方式效果一樣砌左,都會(huì)引起程序閃退
- 如果不是必須這樣,那么可以直接返回nil汇歹,或者使用try-catch-finally語(yǔ)句
@try {
// 容易出錯(cuò)的代碼
// 這一部分代碼,一旦哪一行出錯(cuò)秤朗,立即停止執(zhí)行,跳轉(zhuǎn)到catch中執(zhí)行代碼
} @catch (NSException *exception) {
// 出錯(cuò)之后執(zhí)行的代碼
} @finally {
// 最后執(zhí)行的代碼
// 正確也會(huì)執(zhí)行取视,出錯(cuò)也會(huì)執(zhí)行
}
捕獲異常
- 開(kāi)發(fā)中我們經(jīng)常需要捕獲異常硝皂,需要查看異常發(fā)生時(shí)的調(diào)用棧信息
- 在OC中作谭,獲取異常信息有一個(gè)方法:
在程序剛啟動(dòng)的時(shí)候設(shè)置捕捉異常的回調(diào)
- NSSetUncaughtExceptionHandler
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 設(shè)置捕捉異常的回調(diào)
NSSetUncaughtExceptionHandler(handleException);
return YES;
}
/**
* 攔截異常
*/
void handleException2(NSException *exception)
{
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info[@"callStack"] = [exception callStackSymbols]; // 調(diào)用棧信息(錯(cuò)誤來(lái)源于哪個(gè)方法)
info[@"name"] = [exception name]; // 異常名字
info[@"reason"] = [exception reason]; // 異常描述(報(bào)錯(cuò)理由)
//[info writeToFile: atomically:];// 寫(xiě)入沙盒
}
// 如果想有異常的時(shí)候程序不閃退
void handleException(NSException *exception)
{
[[UIApplication sharedApplication].delegate performSelector:@selector(handle)];
}
- (void)handle
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"程序出錯(cuò)了" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertView show];
// 重新啟動(dòng)RunLoop
[[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
exit(0);
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者