c语言 switch程序崩溃,iOS崩溃异常处理(NSUncaughtExceptionHandler)

简介:

利用NSSetUncaughtExceptionHandler可以用来处理异常崩溃。崩溃报告系统会用NSSetUncaughtExceptionHandler方法设置全局的异常处理器,第三方crash收集平台Bugly和友盟等都是基于这个原理实现的。

详解:

NSSetUncaughtExceptionHandler

2a8b6c9b5a59

NSSetUncaughtExceptionHandler是苹果官方提供的一个C函数,NSSetUncaughtExceptionHandler接收的参数是一个函数指针,该函数需要我们实现。当程序发生异常崩溃时,该函数会得到调用,所以我们对于异常的处理都是写在这个函数里。但是他无法处理内存访问错误、重复释放等错误,因为这些错误发送的SIGNAL。所以需要处理这些SIGNAL,所以我们还要设置处理SIGNAL的函数。

针对NSSetUncaughtExceptionHandle的异常处理

我们只需要在App启动时候(AppDelegate中)调用NSSetUncaughtExceptionHandler就好了,并传入我们自己写好的HandleException函数(C语言):

NSSetUncaughtExceptionHandler(&HandleException);

当系统抛出NSException的时候,因为我们已经将自己的HandleException函数传给系统作为UncaughtExceptionHandler了,所以这时系统就会调用我们的函数,并将这个Exception作为参数传给我们定义的函数:void uncaughtExceptionHandler(NSException * exception){

//获取系统当前时间,(注:用[NSDate date]直接获取的是格林尼治时间,有时差)

NSDateFormatter *formatter =[[NSDateFormatter alloc] init];

[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *crashTime = [formatter stringFromDate:[NSDate date]];

[formatter setDateFormat:@"HH-mm-ss"];

NSString *crashTimeStr = [formatter stringFromDate:[NSDate date]];

[formatter setDateFormat:@"yyyyMMdd"];

NSString *crashDate = [formatter stringFromDate:[NSDate date]];

//异常的堆栈信息

NSArray *stackArray = [exception callStackSymbols];

//出现异常的原因

NSString *reason = [exception reason];

//异常名称

NSString *name = [exception name];

//拼接错误信息

NSString *exceptionInfo = [NSString stringWithFormat:@"CrashTime: %@\nException reason: %@\nException name: %@\nException call stack:%@\n", crashTime, name, reason, stackArray];

//把错误信息保存到本地文件,设置errorLogPath路径下

//并且经试验,此方法写入本地文件有效。

NSString *errorLogPath = [NSString stringWithFormat:@"%@/CrashLogs/%@/", NSDocumentsDirectory(), crashDate];

NSFileManager *manager = [NSFileManager defaultManager];

if (![manager fileExistsAtPath:errorLogPath]) {

[manager createDirectoryAtPath:errorLogPath withIntermediateDirectories:true attributes:nil error:nil];

}

errorLogPath = [errorLogPath stringByAppendingFormat:@"%@.log",crashTimeStr];

NSError *error = nil;

NSLog(@"%@", errorLogPath);

BOOL isSuccess = [exceptionInfo writeToFile:errorLogPath atomically:YES encoding:NSUTF8StringEncoding error:&error];

if (!isSuccess) {

NSLog(@"将crash信息保存到本地失败: %@", error.userInfo);

}

}

针对void (*signal(int, void (*)(int)))(int)的异常 处理

void (*signal(int, void (*)(int)))(int)也是iOS SDK提供的函数,该函数接受两个参数,一个int型:代表SIGNAL的类型

第二个参数也是一个函数指针,和NSSetUncaughtExceptionHandler的一样,该函数需要我们实现。当程序发生异常崩溃时,该函数会得到调用。

首先在- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中调用InstallUncaughtExceptionHandler()初始化,可以看到其中包含刚介绍的两个C函数:NSSetUncaughtExceptionHandler和void (*signal(int, void (*)(int)))(int),这两个就是设置拦截异常的函数void InstallUncaughtExceptionHandler(void) {

NSSetUncaughtExceptionHandler(&HandleException);

//注册程序由于abort()函数调用发生的程序中止信号

signal(SIGABRT, SignalHandler);

//注册程序由于非法指令产生的程序中止信号

signal(SIGILL, SignalHandler);

//注册程序由于无效内存的引用导致的程序中止信号

signal(SIGSEGV, SignalHandler);

//注册程序由于浮点数异常导致的程序中止信号

signal(SIGFPE, SignalHandler);

//注册程序由于内存地址未对齐导致的程序中止信号

signal(SIGBUS, SignalHandler);

//程序通过端口发送消息失败导致的程序中止信号

signal(SIGPIPE, SignalHandler);

}

可以看到对于系统抛出的NSException类型的异常这里是用HandleException函数来处理的,对于系统发出的SIGNAL这里是用SignalHandler函数来处理的,这里对6种信号(SIGABRT-程序中止命令中止信号、SIGILL--程序非法指令信号、SIGSEGV--程序无效内存中止信号、SIGFPE--程序浮点异常信号、SIGBUS--程序内存字节未对齐中止信号、SIGPIPE--程序Socket发送失败中止信号)设置了处理函数,其他信号在没有处理函数的情况下,程序可以指定两种行为:忽略这个信号SIG_IGN或者用默认的处理函数SIG_DFL,下面是这两个函数的具体实现:void SignalHandler(int signal){

// 递增的一个全局计数器,很快很安全,防止并发数太大

int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);

if (exceptionCount > UncaughtExceptionMaximum){

return;

}

// 获取堆栈信息的数组

NSArray *callStack = [UncaughtExceptionHandler backtrace];

// 将堆栈信息放入exception的userInfo中

NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:signal]

forKey:UncaughtExceptionHandlerSignalKey];

[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];

//将signal包装成exception

NSException *exp = [NSException exceptionWithName:UncaughtExceptionHandlerSignalExceptionName

reason:[NSString stringWithFormat:@"Signal %d was raised.", signal]

userInfo:userInfo];

//将exception传入handleException方法中处理

[[[UncaughtExceptionHandler alloc] init] performSelectorOnMainThread:@selector(handleException:)

withObject:exp

waitUntilDone:YES];

}

通过这两个函数可知,他们都是对接收到的exception或signal进行了一些处理之后,最后都转由UncaughtExceptionHandler类的- (void)handleException:(NSException *)exception方法来处理

处理异常:- (void)handleException:(NSException *)exception{

[self validateAndSaveCriticalApplicationData];

UIAlertView *alert =

[[UIAlertView alloc] initWithTitle:@"处理异常"

message:[NSString stringWithFormat:@"你可以继续,但应用程序可能不稳定.\n\n调试细节如下:\n%@\n%@",[exception reason],[[exception userInfo] objectForKey:UncaughtExceptionHandlerAddressesKey]]

delegate:self

cancelButtonTitle:@"离开"

otherButtonTitles:@"继续", nil];

[alert show];

//当接收到异常处理消息时,让程序开始runloop,防止程序死亡

CFRunLoopRef runLoop = CFRunLoopGetCurrent();

CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);

while (!dismissed) {

for (NSString *mode in (__bridge NSArray *)allModes){

CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);

}

}

//当点击弹出视图的Cancel按钮哦,会将isDimissed设置为YES,上边的循环就会跳出,以下代码才会执行

CFRelease(allModes);

//此处将异常重新转交系统处理,即程序会在用户点击弹出视图的Cancel按钮时Crash退出

NSSetUncaughtExceptionHandler(NULL);

signal(SIGABRT, SIG_DFL);

signal(SIGILL, SIG_DFL);

signal(SIGSEGV, SIG_DFL);

signal(SIGFPE, SIG_DFL);

signal(SIGBUS, SIG_DFL);

signal(SIGPIPE, SIG_DFL);

if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName]){

kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);

}else{

[exception raise];

}

}

在- (void)handleException:(NSException *)exception方法中,先是用弹窗提示用户错误并显示错误信息,然后让程序开始runloop,防止程序死亡,根据用户的选择来确定是否终止runloop。这种方式会更加友好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值