使用@try、catch捕獲異常: app
如下是最簡單的代碼寫法,其中@finally能夠去掉: ide
1
2
3
4
5
6
7
8
9
|
@try {
// 可能會出現崩潰的代碼
}
@catch (NSException *exception) {
// 捕獲到的異常exception
}
@finally {
// 結果處理
}
|
在這裏舉多一具比較詳細的方法,拋出異常: spa
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(@"我必定會執行");
}
// 4
// 這裏必定會執行
NSLog(@"try");
|
tryTwo方法代碼: component
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]; // 程序到這裏會崩
}
@catch (NSException *exception) {
// 6
// @throw exception; // 拋出異常,即由上一級處理
// 7
NSLog(@"%s\n%@", __FUNCTION__, exception);
}
@finally {
// 8
NSLog(@"tryTwo - 我必定會執行");
}
// 9
// 若是拋出異常,那麼這段代碼則不會執行
NSLog(@"若是這裏拋出異常,那麼這段代碼則不會執行");
}
|
爲了方便你們理解,我在這裏再說明一下狀況:
若是6拋出異常,那麼執行順序爲:1->5->6->8->3->4
若是6沒拋出異常,那麼執行順序爲:1->5->7->8->9->3->4 orm
2)部分狀況的崩潰咱們是沒法避免的,就算是QQ也會有崩潰的時候。所以咱們能夠在程序崩潰以前作一些「動做」(收集錯誤信息),如下例子是把捕獲到的異常發送至開發者的郵箱。 ci
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);
return YES;
}
void UncaughtExceptionHandler(NSException *exception) {
/**
* 獲取異常崩潰信息
*/
NSArray *callStack = [exception callStackSymbols];
NSString *reason = [exception reason];
NSString *name = [exception name];
NSString *content = [NSString stringWithFormat:@"========異常錯誤報告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[callStack componentsJoinedByString:@"\n"]];
/**
* 把異常崩潰信息發送至開發者郵件
*/
NSMutableString *mailUrl = [NSMutableString string];
[mailUrl appendString:@"mailto:test@qq.com"];
[mailUrl appendString:@"?subject=程序異常崩潰,請配合發送異常報告,謝謝合做!"];
[mailUrl appendFormat:@"&body=%@", content];
// 打開地址
NSString *mailPath = [mailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];
}
|