Uncaught exception handler not called

倾然丶 夕夏残阳落幕 提交于 2019-12-06 07:00:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!