前言:在開發(fā)APP時(shí)妒茬,我們通常都會(huì)需要捕獲異常,防止應(yīng)用程序突然的崩潰蔚晨,防止給予用戶不友好的體驗(yàn)郊闯。其實(shí)Objective-C的異常處理方法和JAVA的雷同,懂JAVA的朋友一看就懂团赁。我為什么要寫這篇博文呢?因?yàn)槲野l(fā)現(xiàn)百度上的介紹方法怀挠,很多都不是我想要的,而我想要的又說得不清楚吞滞,重點(diǎn)是大家都是直接復(fù)制別人的代碼。佩捞。一忱。于是不多說,大家往下看~~~
以下程序已測(cè)試并通過:
設(shè)備:iOS 8模擬器中
開發(fā)工具:XCode6.1
使用@try仪吧、catch捕獲異常:
以下是最簡(jiǎn)單的代碼寫法,其中@finally可以去掉:
1
2
3
4
5
6
7
8
9@try{
//?可能會(huì)出現(xiàn)崩潰的代碼
}
@catch(NSException?*exception)?{
//?捕獲到的異常exception
}
@finally?{
//?結(jié)果處理
}
在這里舉多一具比較詳細(xì)的方法,拋出異常:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16@try{
//?1
[self?tryTwo];
}
@catch(NSException?*exception)?{
//?2
NSLog(@"%s\n%@",?__FUNCTION__,?exception);
//????????@throw?exception;?//?這里不能再拋異常
}
@finally?{
//?3
NSLog(@"我一定會(huì)執(zhí)行");
}
//?4
//?這里一定會(huì)執(zhí)行
NSLog(@"try");
tryTwo方法代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22-?(void)tryTwo
{
@try{
//?5
NSString?*str?=?@"abc";
[str?substringFromIndex:111];//?程序到這里會(huì)崩
}
@catch(NSException?*exception)?{
//?6
//????????@throw?exception;?//?拋出異常,即由上一級(jí)處理
//?7
NSLog(@"%s\n%@",?__FUNCTION__,?exception);
}
@finally?{
//?8
NSLog(@"tryTwo?-?我一定會(huì)執(zhí)行");
}
//?9
//?如果拋出異常,那么這段代碼則不會(huì)執(zhí)行
NSLog(@"如果這里拋出異常刻获,那么這段代碼則不會(huì)執(zhí)行");
}
為了方便大家理解,我在這里再說明一下情況:
如果6拋出異常,那么執(zhí)行順序?yàn)椋?->5->6->8->3->4
如果6沒拋出異常扎谎,那么執(zhí)行順序?yàn)椋?->5->7->8->9->3->4
2)部分情況的崩潰我們是無法避免的解藻,就算是QQ也會(huì)有崩潰的時(shí)候螟左。因此我們可以在程序崩潰之前做一些“動(dòng)作”(收集錯(cuò)誤信息)巷嚣,以下例子是把捕獲到的異常發(fā)送至開發(fā)者的郵箱。
AppDelegate.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26-?(BOOL)application:(UIApplication?*)application?didFinishLaunchingWithOptions:(NSDictionary?*)launchOptions?{
//?Override?point?for?customization?after?application?launch.
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
returnYES;
}
void?UncaughtExceptionHandler(NSException?*exception)?{
/**
*??獲取異常崩潰信息
*/
NSArray?*callStack?=?[exception?callStackSymbols];
NSString?*reason?=?[exception?reason];
NSString?*name?=?[exception?name];
NSString?*content?=?[NSString?stringWithFormat:@"========異常錯(cuò)誤報(bào)告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[callStack?componentsJoinedByString:@"\n"]];
/**
*??把異常崩潰信息發(fā)送至開發(fā)者郵件
*/
NSMutableString?*mailUrl?=?[NSMutableString?string];
[mailUrl?appendString:@"mailto:test@qq.com"];
[mailUrl?appendString:@"?subject=程序異常崩潰嗤放,請(qǐng)配合發(fā)送異常報(bào)告恨课,謝謝合作!"];
[mailUrl?appendFormat:@"&body=%@",?content];
//?打開地址
NSString?*mailPath?=?[mailUrl?stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication?sharedApplication]?openURL:[NSURL?URLWithString:mailPath]];
}