1.有些异常是无法避免的。
Appdelegate.m
- (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];
NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *mailPath = [mailUrl stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];
}
<br /><br /><br />
2.有些异常是可以捕获的。
使用@try、catch捕获异常:
以下是最简单的代码写法,其中@finally可以去掉:
@try {
// 可能会出现崩溃的代码
}
@catch (NSException *exception) {
// 捕获到的异常exception
}
@finally {
// 结果处理
}
我们在不符合条件的情况下抛出异常:
@throw [NSException exceptionWithName:@"异常名称" reason:@"异常原因" userInfo:nil];
这样我们就可以用@try去捕获相应的异常并加以处理了。