Managing Unhandled Exceptions and Crashes on Mac Cocoa

I am implementing a Mac application and want to handle the following events:

  • Unhandled exception
  • Program crash (dcc memory error)

If I find them, I can send me detailed information to analyze and correct the errors using one of the Crash handlers I found . Alas, I canโ€™t understand how to catch failures and exceptions.

  • First question: Should I distinguish exceptions from failures? Or is it enough to detect an exception?
  • How can I catch exceptions and / or crashes redirecting them to my handler?

PS I tried to follow in my class MyApp

NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); signal(SIGABRT, SignalHandler); signal(SIGILL, SignalHandler); signal(SIGSEGV, SignalHandler); signal(SIGFPE, SignalHandler); signal(SIGBUS, SignalHandler); signal(SIGPIPE, SignalHandler); 

but that will not work. Every time it crashes, it goes into the debugger without classification SignalHandler or uncaughtExceptionHandler

+4
source share
1 answer

I found that the best way is to create a simple exception handling delegate class as this allows you to throw exceptions from IBAction methods.

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 

You need to add the ExceptionHandling.framework project to the project.

+3
source

All Articles