捕获异常


#include 
#include 


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    /*
     注意::::::!!!!!
     
     iOS SDK提供的函数是NSSetUncaughtExceptionHandler来进行异常处理。但是无法处理内存访问错误、重复释放等错误,因为这些错误发送的SIGNAL。所以需要处理这些SIGNAL
     */
    
    NSSetUncaughtExceptionHandler(&HandleException);
    
    return YES;
}
void HandleException(NSException *exception)
{
    
    NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
    NSString *reason = [exception reason];//非常重要,就是崩溃的原因
    NSString *name = [exception name];//异常类型
    NSString *excpCnt = [NSString stringWithFormat:@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr];
    NSLog(@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr);
    
    //保存日志
    NSArray *dieArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dirPath = dieArr[0];
    NSString *logDir = [dirPath stringByAppendingString:@"/CrashLog"];
    
    BOOL isExistLogDir =  YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:logDir]) {
        isExistLogDir = [fileManager createDirectoryAtPath:logDir withIntermediateDirectories:NO attributes:nil error:nil];
    }
    if (isExistLogDir) {
        NSString *logPath = [logDir stringByAppendingString:@"/crashLog.txt"];
        [excpCnt writeToFile:logPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    
    //第二种方法,询问用户是否发送邮件给开发者
    NSString *urlStr = [NSString stringWithFormat:@"mailto://[email protected]?subject=bug报告%错误详情:%@",excpCnt];
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [[UIApplication sharedApplication] openURL:url];

}




你可能感兴趣的:(捕获异常)