"IOS" exception capture denial of Flash retreat application calmly crash Uncaughtexceptionhandler

Source: Internet
Author: User

Although people do not want to see the program crashes, but may crash is the reality of every application must face, since the collapse has occurred, can not stop, then we let it collapse also a point of light.

The IOS SDK provides an out-of-the-box function Nssetuncaughtexceptionhandler for exception handling, but with very limited functionality, most of the causes of crashes such as memory access errors, repeated releases, etc. Because of this error it throws signal, so it has to be done specifically for signal processing. First define a Uncaughtexceptionhandler class with the following code:

#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface uncaughtexceptionhandler:nsobject{    BOOL dismissed;} + (void) Installuncaughtexceptionhandler; @end
Using Nssetuncaughtexceptionhandler, when the program exits unexpectedly, can be processed first, and then do some custom actions, such as the following paragraph of code, is written on the Internet, directly in the event of an exception to send a message to someone, </span >void uncaughtexceptionhandlers (NSException *exception);

#import "UncaughtExceptionHandler.h" #include <libkern/OSAtomic.h> #include <execinfo.h>nsstring * const Uncaughtexceptionhandlersignalexceptionname = @ "Uncaughtexceptionhandlersignalexceptionname"; NSString * Const UNCAUGHTEXCEPTIONHANDLERSIGNALKEY = @ "Uncaughtexceptionhandlersignalkey"; NSString * Const UNCAUGHTEXCEPTIONHANDLERADDRESSESKEY = @ "Uncaughtexceptionhandleraddresseskey"; volatile int32_t Uncaughtexceptioncount = 0;const int32_t uncaughtexceptionmaximum = 10;const Nsinteger Uncaughtexceptionhandlerskipaddresscount = 4;const Nsinteger uncaughtexceptionhandlerreportaddresscount = 5; nsstring* Getappinfo () {NSString *appinfo = [NSString stringwithformat:@ ' App:%@%@ (%@) \ndevice:%@\nos Version:%@                         %@\n ", [[NSBundle Mainbundle] objectforinfodictionarykey:@" Cfbundledisplayname "], [[NSBundle Mainbundle] objectforinfodictionarykey:@ "cfbundleshortversionstring"], [[Nsbund Le Mainbundle] Objectforinfodictionarykey:@ "Cfbundleversion"], [Uidevice Currentdevice].model, [Uidevi    Ce currentdevice].systemname, [uidevice currentdevice].systemversion];    [Uidevice Currentdevice].uniqueidentifier];    NSLog (@ "Crash!!!!%@", appInfo); return appInfo;} void Mysignalhandler (int signal) {int32_t Exceptioncount = OSAtomicIncrement32 (&uncaughtexceptioncount);    Exceptioncount > Uncaughtexceptionmaximum) {return;} if (signal==11) {//Compare the pit Dad is a problem I have encountered only iPhone5 problems but I have no iPhone5 on this side of the test can be directly log memory is not enough to delete a few applications so add this sentence
        Uialertview * TIP2 = [[Uialertview alloc]initwithtitle:@ "possible cause: Key" message:@ "Out of Memory" Delegate:nil Cancelbuttontitle:        @ "OK" otherbuttontitles:nil];        [Tip2 show];    [TIP2 release]; } nsmutabledictionary *userinfo = [nsmutabledictionary dictionarywithobject:[nsnumber numberWithInt:signal] ForKey: Uncaughtexceptionhandlersignalkey]; Nsarray *callstack = [Uncaughtexceptionhandler backtrace]; [UserInfo Setobject:callstack Forkey:uncaughtexceptionhandleraddresseskey]; [[[[[Uncaughtexceptionhandler alloc] init] autorelease] Performselectoronmainthread: @selector (handleexception:) wit Hobject: [nsexception exceptionwithname:uncaughtexceptionhandlersignalexceptionname Reason: [NSString s Tringwithformat:nslocalizedstring (@ "Signal%d was raised.\n" @ "%@", nil), Signal, get AppInfo ()] UserInfo: [nsdictionary dictionarywithobject:[nsnumber numberwithint:signal] Forkey:uncau Ghtexceptionhandlersignalkey]] [waituntildone:yes];} @implementation uncaughtexceptionhandler+ (void) installuncaughtexceptionhandler{signal (SIGABRT, Mysignalhandler); Signal (Sigill, mysignalhandler); signal (SIGSEGV, mysignalhandler); signal (SIGFPE, mysignalhandler); Signal (Sigbus, Mysignalhandler); signal (sigpipe, mysignalhandler);}    + (Nsarray *) backtrace{void* callstack[128];    int frames = BackTrace (callstack, 128);    Char **strs = Backtrace_symbols (callstack, frames);    int i;    Nsmutablearray *backtrace = [Nsmutablearray arraywithcapacity:frames];         for (i = uncaughtexceptionhandlerskipaddresscount;         I < Uncaughtexceptionhandlerskipaddresscount + Uncaughtexceptionhandlerreportaddresscount;    i++) {[BackTrace addobject:[nsstring stringwithutf8string:strs[i]];    } free (STRs); return backtrace;} -(void) Alertview: (Uialertview *) Analertview Clickedbuttonatindex: (Nsinteger) anindex{if (Anindex = = 0) {dismissed = YES ;}} -(void) HandleException: (NSException *) exception{uIalertview *alert = [[[Uialertview Alloc] initwithtitle:nslocalizedstring (@ "Unhandled exception", nil) Messag  E:[nsstring stringwithformat:nslocalizedstring (@ "can try to Continue but the application is unstable.\n "@"%@\n%@ ", nil ), [exception reason], [[Exception UserInfo] Objectforkey:uncaughtexceptionhandleraddresseskey ]] delegate:self cancelbuttontitle:nslocalizedstring (@ "Quit", nil) otherbuttontitles:nslocalizedstring (@ "Co Ntinue ", nil), nil] autorelease]; [Alert show]; Cfrunloopref Runloop = Cfrunloopgetcurrent (); Cfarrayref allmodes = Cfrunloopcopyallmodes (Runloop), while (!dismissed) {for (NSString *mode in (Nsarray *) allModes) { Cfrunloopruninmode ((cfstringref) mode, 0.001, false);}} Cfrelease (Allmodes); 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 Uncaughtexceptionhandlers (NSException *exception) {Nsarray *arr = [exception callstacksymbols];    NSString *reason = [exception reason];    NSString *name = [exception name]; NSString *urlstr = [nsstring stringwithformat:@ mailto://[email protected]?subject=bug report &body= Thank you for your cooperation!< Br><br><br> "" Error details:<br>%@<br>--------------------------<br>%@<b     R>---------------------<br>%@ ", Name,reason,[arr componentsjoinedbystring:@" <br> "];    Nsurl *url = [Nsurl urlwithstring:[urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];        [[UIApplication sharedapplication] openurl:url]; or straightConnect the code and enter this crash information to further analyze the cause of the error in the console NSLog (@ "1heqin, CRASH:%@", exception); NSLog (@ "Heqin, Stack Trace:%@", [exception Callstacksymbols]);} @end


then inside the delegate file-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) Inside the Launchoptions function

[Uncaughtexceptionhandler Installuncaughtexceptionhandler];    Nssetuncaughtexceptionhandler (&uncaughtexceptionhandlers);



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.