mac app NSSetUncaughtExceptionHandler

On the mac, I found that NSSetUncaughtExceptionHandler can not catch the exception without a dispatch block, but if the crash code in a dispatch block, the crash handler can do. As the below code, the exception produced by method 'crash' can not been caught, but exception produced by method 'dispatchCrash' can been caught.


Code Block
- (void)didClickBtn {
//  [self crash];
  [self dispatchCrash];
}
- (void)dispatchCrash {
  dispatch_async(dispatch_get_main_queue(), ^{
    NSArray *testArray = [NSArray arrayWithObjects:@"test",@"test1", nil];
    NSLog(@"%@", testArray[10]);
  });
}
- (void)crash {
    NSArray *testArray = [NSArray arrayWithObjects:@"test",@"test1", nil];
  NSLog(@"%@", testArray[10]);
}



[Wow, a question that’s more-or-less on-topic for the ExceptionHandling tag. That’s such a rarity. Thank you!]

The handler you register with NSSetUncaughtExceptionHandler is called when an Objective-C exception goes uncaught. That’s why it’s working when you raise the exception from -dispatchCrash. So it’s the -crash case that’s unexpected.

What’s happening here is that AppKit runs all code within its own exception handler. That exception handler logs the exception and then continues running the app. So, the exception does not go unhandled and thus your uncaught exception handler is never called.

This is, IMO, a serious misfeature in AppKit and I encourage you to file a bug requesting that it not do that. Please post your bug number, just for the record.

What are you trying to do in your uncaught exception handler? Most folks who hit this problem are trying to implement their own crash reporter, and that’s something that I also try to discourage. See Implementing Your Own Crash Reporter for the very gory details.

If your goal is simply to get the app to crash in this case, you can do that by subclassing NSApplication and overriding reportException(_:).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
mac app NSSetUncaughtExceptionHandler
 
 
Q