Is there a way to execute code after an uncaught exception in iOS?

I am working on a framework for several applications that implement multi-level logging. It is mainly used in applications used internally to verify communication with other devices, but is also used in some applications that we will distribute.

Is there a way to catch an uncaught exception and quickly execute code to save the exception in a log file? At the moment, the log class simply writes to the file so often, alternating between two files in case of write failure, etc. This works well, but it would be great if he saw that an unhandled exception was thrown, write any unwritten logging to the file, notice that the exception occurred, and write down its details, and then allow the application to crash.

If there is a way to catch unhandled exceptions in the application, I would think it would be something like:

appDidReceiveUnhandledException:(NSException *)exception { //write log to disk //append exception info to log file //rethrow exception } 

If someone can give me an idea or suggestions as to whether this is possible, it would be very helpful.

+7
source share
3 answers

You can add an unhandled exception handler to AppDelegate:

 void HandleExceptions(NSException *exception) { NSLog(@"The app has encountered an unhandled exception: %@", [exception debugDescription]); // Save application data on crash } 

Link to it in AppDelegate didFinishLaunchingWithOptions as:

 NSSetUncaughtExceptionHandler(&HandleExceptions); 
+17
source

You can set your own exception handler by calling NSSetUncaughtExceptionHandler()

You can call it you are application delegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { #ifdef DEBUG NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); #endif ... } 

As you can see, you need to pass a pointer to a function like this:

 void uncaughtExceptionHandler(NSException *exception) { NSLog(@"App Crash:\n%@", exception); NSLog(@"Stack Trace:\n%@", [exception callStackSymbols]); } 
+3
source

You must install an exception handler, this is best done in the application delegate in applicationDidFinishLaunching, i.e.:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSSetUncaughtExceptionHandler(&mExceptionHandler); } - (void)mExceptionHandler(NSException *exception) { NSLog(@"Exception %@", exception); } 
+1
source

All Articles