我正在实施一个Mac App,我想处理以下事件:
>未处理的例外
>程序崩溃(内存错误dcc)
如果我检测到它们,我可以向我发送详细信息,以便使用我发现的Crash Handlers之一来分析和修复错误.唉,我无法弄清楚如何拦截崩溃和异常.
>第一个问题:我是否要将例外与崩溃区分开来?或者检测Exception就足够了?
>如何捕获异常和/或崩溃将它们重定向到我的处理程序?
PS
我试着在我的MyApp课程中关注
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); signal(SIGABRT,SignalHandler); signal(SIGILL,SignalHandler); signal(SIGSEGV,SignalHandler); signal(SIGFPE,SignalHandler); signal(SIGBUS,SignalHandler); signal(SIGPIPE,SignalHandler);
但它不起作用.每次崩溃时,它都会进入调试器而不对SignalHandler或uncaughtExceptionHandler进行分类
解决方法
我发现最好的方法是创建一个简单的异常处理委托类,因为这样可以捕获IBAction方法中的异常.
main.mm:
@interface ExceptionDelegate : NSObject @end static ExceptionDelegate *exceptionDelegate = nil; int main(int argc,char **argv) { int retval = 1; @autoreleasepool { // // Set exception handler delegate // exceptionDelegate = [[ExceptionDelegate alloc] init]; NSExceptionHandler *exceptionHandler = [NSExceptionHandler defaultExceptionHandler]; exceptionHandler.exceptionHandlingMask = NSLogAndHandleEveryExceptionMask; exceptionHandler.delegate = exceptionDelegate; // // Set signal handler // int signals[] = { SIGQUIT,SIGILL,SIGTRAP,SIGABRT,SIGEMT,SIGFPE,SIGBUS,SIGSEGV,SIGSYS,SIGPIPE,SIGALRM,SIGXcpu,SIGXFSZ }; const unsigned numSignals = sizeof(signals) / sizeof(signals[0]); struct sigaction sa; sa.sa_sigaction = signalHandler; sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); for (unsigned i = 0; i < numSignals; i++) sigaction(signals[i],&sa,NULL); .... } .... return retval; } static void signalHandler(int sig,siginfo_t *info,void *context) { logerr(@"Caught signal %d",sig); exit(102); } @implementation ExceptionDelegate - (BOOL)exceptionHandler:(NSExceptionHandler *)exceptionHandler shouldLogException:(NSException *)exception mask:(unsigned int)mask { logerr(@"An unhandled exception occurred: %@",[exception reason]); return YES; } - (BOOL)exceptionHandler:(NSExceptionHandler *)exceptionHandler shouldHandleException:(NSException *)exception mask:(unsigned int)mask { exit(101); // not reached return NO; } @end
您需要将ExceptionHandling.framework添加到项目中.