使用@try、catch捕获异常:

使用@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]];
}