"Turn" http://www.cocoachina.com/ios/20141229/10787.html
Catch exceptions using @try, catch:
Here's the simplest code notation, where @finally can get rid of:
@try { // may appear crash code }@catch (nsexception *exception) { // the caught exception exception }@finally { // result processing }
Here's a more detailed way to throw an exception:
@try { //1[self trytwo];}@catch(NSException *exception) { //2NSLog (@"%s\n%@", __function__, exception);//@throw exception;//you can't throw an exception here .}@finally { //3NSLog (@"I'm sure I'll do it .");}//4//This is going to be done .NSLog (@"Try");
Trytwo Method Code
- (void) trytwo{@try { //5NSString *str =@"ABC"; [Str substringfromindex:111];//The program will collapse here . } @catch(NSException *exception) { //6//@throw exception;//throws an exception, which is handled by the top level//7NSLog (@"%s\n%@", __function__, exception); } @finally { //8NSLog (@"Trytwo-I'm sure I'll do it ."); } //9//If an exception is thrown, then this code does not executeNSLog (@"If an exception is thrown here, then this code will not execute");}
For your convenience, let me explain the situation here:
If 6 throws an exception, then the order of execution is: 1->5->6->8->3->4
If 6 does not throw an exception, then the order of execution is: 1->5->7->8->9->3->4
2) Part of the collapse of the situation we are unavoidable, even QQ will have a crash. So we can do some "action" (Collect the error message) before the program crashes, the following example is to send the caught exception to the developer's mailbox.
Appdelegate.m
-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions {//Override point for customization after application launch.Nssetuncaughtexceptionhandler (&Uncaughtexceptionhandler); returnYES;} voidUncaughtexceptionhandler (NSException *exception) { /** * Get exception crash information*/Nsarray*callstack =[Exception callstacksymbols]; NSString*reason =[Exception reason]; NSString*name =[exception name]; NSString*content = [NSString stringWithFormat:@"======== Exception error report ========\nname:%@\nreason:\n%@\ncallstacksymbols:\n%@", Name,reason,[callstack componentsjoinedbystring:@"\ n"]]; /** * Send abnormal crash information to developer email*/nsmutablestring*mailurl = [nsmutablestringstring]; [Mailurl appendString:@"Mailto:[email protected]"]; [Mailurl appendString:@"subject= program Abnormal crash, please cooperate with send exception report, thank you for your cooperation! "]; [Mailurl AppendFormat:@"&body=%@", content]; //Open AddressNSString *mailpath =[Mailurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; [[UIApplication sharedapplication] Openurl:[nsurl urlwithstring:mailpath];}
iOS catch exceptions, common exception handling methods