2015-05-11 14:54:17 1113浏览
在IOS开发中,我们一般都会需要捕获异常,防止应用程序突然的崩溃,给用户不友好的印象。其实OBJECT-C的异常处理方法和JAVA的雷同,下面我们一起来看看,
以下程序已测试并通过:

设备:IOS8模拟器中
开发工具:XCode6.1
1.
@try {
2.
3. // 可能会出现崩溃的代码
4.
5. }
6.
7. @catch (NSException *exception) {
8.
9. // 捕获到的异常exception
10.
11. }
12.
13. @finally {
14.
15. // 结果处理
16.
17. }
复制代码
在这里举多一具比较详细的方法,抛出异常:
1.
@try {
2. // 1
3. [self tryTwo];
4. }
5. @catch (NSException *exception) {
6. // 2
7. NSLog(@"%s\n%@", __FUNCTION__, exception);
8. // @throw exception; // 这里不能再抛异常
9. }
10. @finally {
11. // 3
12. NSLog(@"我一定会执行");
13. }
14. // 4
15. // 这里一定会执行
16. NSLog(@"try");
复制代码
tryTwo方法代码:
1. - (void)tryTwo
2.
3. {
4.
5. @try {
6.
7. // 5
8.
9. NSString *str = @"abc";
10.
11. [str substringFromIndex:111]; // 程序到这里会崩
12.
13. }
14.
15. @catch (NSException *exception) {
16.
17. // 6
18.
19. // @throw exception; // 抛出异常,即由上一级处理
20.
21. // 7
22.
23. NSLog(@"%s\n%@", __FUNCTION__, exception);
24.
25. }
26.
27. @finally {
28.
29. // 8
30.
31. NSLog(@"tryTwo - 我一定会执行");
32.
33. }
34.
35.
36.
37. // 9
38.
39. // 如果抛出异常,那么这段代码则不会执行
40.
41. NSLog(@"如果这里抛出异常,那么这段代码则不会执行");
42.
43. }
复制代码
为了方便大家理解,我在这里再说明一下情况:
如果6抛出异常,那么执行顺序为:1->5->6->8->3->4
如果6没抛出异常,那么执行顺序为:1->5->7->8->9->3->4
2)部分情况的崩溃我们是无法避免的,就算是QQ也会有崩溃的时候。因此我们可以在程序崩溃之前做一些“动作”(收集错误信息),以下例子是把捕获到的异常发送至开发者的邮箱。
1.
AppDelegate.m
2.
3. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
4. // Override point for customization after application launch.
5. NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
6. return YES;
7. }
8.
9. void UncaughtExceptionHandler(NSException *exception) {
10. /**
11. * 获取异常崩溃信息
12. */
13. NSArray *callStack = [exception callStackSymbols];
14. NSString *reason = [exception reason];
15. NSString *name = [exception name];
16. NSString *content = [NSString stringWithFormat:@"========异常错误报告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[callStack componentsJoinedByString:@"\n"]];
17.
18. /**
19. * 把异常崩溃信息发送至开发者邮件
20. */
21. NSMutableString *mailUrl = [NSMutableString string];
22. [mailUrl appendString:@"mailto:test@qq.com"];
23. [mailUrl appendString:@"?subject=程序异常崩溃,请配合发送异常报告,谢谢合作!"];
24. [mailUrl appendFormat:@"&body=%@", content];
25. // 打开地址
26. NSString *mailPath = [mailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
27. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];
28. }