异常处理
- 抛出异常。此时程序会强制停止
@throw [NSException exceptionWithName:@"牛逼的错误" reason:@"方法找不到" userInfo:nil];
[NSException raise:@"牛逼的错误" format:@"%s",__func__];
- 拦截异常
@try {
@[][0];
} @catch (NSException *exception) {
NSLog(@"代码有异常-%@",exception);
} @finally {
NSLog(@"finally");
}
- 如果try里面的代码有错误,会执行catch,然后执行finally;如果try没有错误,执行完try,直接执行finally
崩溃统计分析
- 方法一。在main函数中拦截崩溃。不过一般不这么干。
int main(int argc, char * argv[]) {
@try {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
} @catch (NSException *exception) {
NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *fileName = [file stringByAppendingPathComponent:@"exception"];
[[exception callStackSymbols] writeToFile:fileName atomically:YES];
} @finally {
}
}
- 方法二。在appDelegate中拦截异常。在崩溃之前拦截。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSSetUncaughtExceptionHandler(handleException);
return YES;
}
void handleException(NSException *exception){
NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSLog(@"file--%@",file);
NSString *fileName = [file stringByAppendingPathComponent:@"exception"];
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info[@"callStack"] = [exception callStackSymbols];
info[@"name"] = [exception name];
info[@"reason"] = [exception reason];
[info writeToFile:fileName atomically:YES];
}
弹出提醒的方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSSetUncaughtExceptionHandler(handleException);
return YES;
}
void handleException(NSException *exception){
[[UIApplication sharedApplication].delegate performSelector:@selector(handle)];
}
-(void)handle{
UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"哈哈" message:@"我是闪退前的挣扎" delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
[view show];
[[NSRunLoop currentRunLoop]addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop]run];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(@"点击了好的");
exit(0);
}