標籤:
【轉】http://www.cocoachina.com/ios/20141229/10787.html
使用@try、catch捕獲異常:
以下是最簡單的代碼寫法,其中@finally可以去掉:
@try { // 可能會出現崩潰的代碼}@catch (NSException *exception) { // 捕獲到的異常exception}@finally { // 結果處理}
在這裡舉多一具比較詳細的方法,拋出異常:
@try { // 1 [self tryTwo];}@catch (NSException *exception) { // 2 NSLog(@"%s\n%@", __FUNCTION__, exception);// @throw exception; // 這裡不能再拋異常}@finally { // 3 NSLog(@"我一定會執行");}// 4// 這裡一定會執行NSLog(@"try");
tryTwo方法代碼
- (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
2)部分情況的崩潰我們是無法避免的,就算是QQ也會有崩潰的時候。因此我們可以在程式崩潰之前做一些“動作”(收集錯誤資訊),以下例子是把捕獲到的異常發送至開發人員的郵箱。
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:[email protected]"]; [mailUrl appendString:@"?subject=程式異常崩潰,請配合發送異常報告,謝謝合作!"]; [mailUrl appendFormat:@"&body=%@", content]; // 開啟地址 NSString *mailPath = [mailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];}
iOS捕獲異常,常用的異常處理方法