问题
I'm trying to catch exceptions on my Mac app so that I can log them in a custom log file. I'm implementing the exception handler like this:
void uncaughtExceptionHandler(NSException *exception) {
NSLog(@"It Works!");
}
And I'm setting it in my -applicationDidFinishLaunching:
method like this:
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
Then I cause an exception to test it like this:
[[NSArray arrayWithObject:@"object"] objectAtIndex:1];
The exception gets logged to the console, but my exception handler is not being called.
Any ideas?
回答1:
The solution is to use the ExceptionHandling
framework. Here's how I did it:
In -applicationDidFinishLaunching:
[[NSExceptionHandler defaultExceptionHandler] setExceptionHandlingMask:NSLogAndHandleEveryExceptionMask];
[[NSExceptionHandler defaultExceptionHandler] setDelegate:self];
Then in my App Delegate class I implement to two delegate methods,
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldLogException:(NSException *)exception mask:(NSUInteger)aMask
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldHandleException:(NSException *)exception mask:(NSUInteger)aMask
Now I can catch all exceptions!
回答2:
AppKit has its own high-level exception handler on the main thread that is catching the exception first. You can subclass NSApplication
and override -reportException:
to get a chance to do something with it.
Your exception handler may still get called on other threads, though.
Reference: Tim Wood's message on macosx-dev back in 1999.
来源:https://stackoverflow.com/questions/9797922/uncaught-exception-handler-not-called