How can I stop HIToolbox from catching my exceptions?
Asked Answered
E

2

5

This question follows on from my other question on why my app isn't being brought down by exceptions.

The Problem

When an exception is thrown on the main thread via an Action, the app still doesn't crash.

As per Dave's answer to my original question, I've implemented the reportException category on NSApplication and set the uncaught exception handler.

Code

I've got the following in my app delegate, which I've hooked up to a button in my UI to test.

-(IBAction)crashOnMainThread:(id)sender {
    [self performSelectorOnMainThread:@selector(crash) withObject:nil waitUntilDone:YES];
}

-(void)crash {
    // To test out the exception handling
    [NSException raise:NSInternalInconsistencyException format:@"This should crash the app."];
}

When I press the button, my app doesn't crash. When I look at the console log, I see this:

06/09/2010 14:12:25 EHTest1[26384]  HIToolbox: ignoring exception 'This should crash the app.' that raised inside Carbon event dispatch
(
    0   CoreFoundation                      0x00007fff80ab4cc4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x00007fff819560f3 objc_exception_throw + 45
    2   CoreFoundation                      0x00007fff80ab4ae7 +[NSException raise:format:arguments:] + 103
    3   CoreFoundation                      0x00007fff80ab4a74 +[NSException raise:format:] + 148
    4   EHTest1                             0x00000001000010e3 -[EHTest1_AppDelegate crashLapsus] + 63
    5   Foundation                          0x00007fff88957c25 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] + 234
    6   Foundation                          0x00007fff8896ad48 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 143
    7   EHTest1                             0x0000000100001030 -[EHTest1_AppDelegate crashOnMainThread:] + 60
    8   AppKit                              0x00007fff85c7e152 -[NSApplication sendAction:to:from:] + 95
    9   AppKit                              0x00007fff85ca26be -[NSMenuItem _corePerformAction] + 365

    ** Snip **

It looks like Carbon is catching the exception, which is really annoying.

This suggests that for any action code, you need to immediately run it in a background thread so any exceptions are registered as uncaught. Huh? I've not seen any code that's structured like this.

What I've tried

Crashing the app with a delay so it's not connected to a UI element. It crashes fine.

I've tried installing a custom NSExceptionHandler using this in my app delegate:

-(BOOL)exceptionHandler:(NSExceptionHandler *)sender 
  shouldHandleException:(NSException *)exception 
                   mask:(unsigned int)aMask {
      abort();
      return YES;
}

-(void)applicationWillFinishLaunching:(NSNotification *)aNotification {
      NSExceptionHandler *handler = [NSExceptionHandler defaultExceptionHandler];
      [handler setExceptionHandlingMask:NSLogAndHandleEveryExceptionMask];
      [handler setDelegate:self];
}

the problem here is it crashes on every exception, whether it's caught or not.

If I try and check the mask and don't crash on a caught exception, I'm back to square 1 as it seems that HIToolbox catches the exception in exactly the same way as a try/catch block would.

Questions

  • How can I stop HIToolbox catching the exceptions so that my app uses the uncaught exception handler and crashes?
  • Is it OK to be running code that's in the same call stack as an action? Surely this is OK?
  • If it's not OK, what's the alternative?

This is driving me up the wall, so any help would be much appreciated.

Earth answered 6/9, 2010 at 14:59 Comment(3)
Why would you want your app to crash if there is an uncaught exception? Those exceptions are caught and logged for you, so that the app does not crash. Just set a breakpoint on [NSException raise] and objc_exception_throw to debug your exceptions, no need to crash there.Decarbonize
That's OK for applications you're debugging. But what about when it's in production and something goes wrong? I want my app to crash the minute something's up so the user can report it, I become aware of it (if I'm not already) and I fix it, pronto.Earth
Just as an FYI this doesn't appear to be an issue anymore (macOS 10.14). If you set ` [[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"NSApplicationCrashOnExceptions": @YES }];` crashes are being caught correctly AFAICT.Inform
N
6

I answered your last question on this subject, and ran into the same problem with Carbon's HIToolbox catching exceptions thrown by IBActions.

First, undo everything I mentioned in my previous answer. It doesn't work with IBActions for some reason. My hunch is that HIToolbox lives lower on the exception-handling-chain, and gets any IBAction/GUI exceptions before NSApplication has the opportunity to. Any custom exception-handling function you can register with NSSetUncaughtExceptionHandler() lives (I believe) at the top of the chain.

You're on the right track with NSExceptionHandling:

  1. Add the ExceptionHandling.framework to your Xcode Project
  2. #import "ExceptionHandlerDelegate.h" into your AppDelegate.m (or a custom Singleton exception class)

Inside AppDelegate.m:

// Very first message sent to class
+ (void)initialize
{
    NSExceptionHandler *exceptionHandler = [NSExceptionHandler defaultExceptionHandler];
    unsigned int handlingMask = NSLogAndHandleEveryExceptionMask;
    [exceptionHandler setExceptionHandlingMask:handlingMask];
    [exceptionHandler setDelegate:self];

    // ...
}


#pragma mark -
#pragma mark NSExceptionHandler Delegate Methods

// Called 1st: Should NSExceptionHandler log the exception?
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldLogException:(NSException *)exception mask:(unsigned int)aMask
{
    // ...log NSException if desired...

    return NO;  // Changes to YES if NSExceptionHandler should handle logging
}

// Called 2nd: Should NSExceptionHandler handle the exception?
- (BOOL)exceptionHandler:(NSExceptionHandler *)sender shouldHandleException:(NSException *)exception mask:(unsigned int)aMask
{
    // ...crash your app here (e.g. [NSApp terminate:self]; )

    // ...or handle the NSException and return YES/NO accordingly

    return NO;  // If app crashed, never gets returned - should crash before that
}

The NSLogAndHandleEveryExceptionMask flag tells NSExceptionHandler to capture every exception it can (for your app only, I believe), regardless of where on the exception chain it exists.

This means that @catch/@try/@finally blocks won't work, because the NSHandleOtherExceptionMask flag tells NSExceptionHandler to capture "everything below it" on the exception-handler chain. You can remove that flag, but then HIToolKit will probably get any IBAction exceptions again, since it appears to be lower on said chain.

Apple's docs have info about the flags: NSExceptionHandler docs

So when an NSException is raised (anywhere in your app AFAIK), and NSLogAndHandleEveryExceptionMask is set, these are called in the delegate in-order:

  1. -exceptionHandler:shouldLogException:mask: is called first.
  2. -exceptionHandler:shouldHandleException:mask: is called second.

Just put your "crash code" inside the second delegate method and you should be OK.


Helpful article: Understanding Exceptions and Handlers in Cocoa


The reason I think you were having trouble getting NSExceptionHandler's delegate to work is because it's NOT compatible with a custom method set with NSSetUncaughtExceptionHandler(), which was part of the answer in my previous question. Per Apple:

The NSExceptionHandler class provides facilities for monitoring and debugging exceptional conditions in Objective-C programs. It works by installing a special uncaught exception handler via the NSSetUncaughtExceptionHandler function. Consequently, to use the services of NSExceptionHandler, you must not install your own custom uncaught exception handler.

It also probably doesn't work well when you override NSApplication's -reportException: method.

Lastly, there doesn't appear to be a need to use @catch/@try/@finally (also part of my previous answer). Configuring NSExceptionHandler inside +initialize appears to "kick in" immediately, unlike overriding NSApplication's -reportException: method.

Nato answered 16/11, 2010 at 22:29 Comment(4)
Wow, Dave. Thanks for an exceptionally detailed and well articulated answer. I'll fix this in my app with your suggestions when I can get around to it. I'll let you know how I get on with it. Lots to digest. Thanks again!Earth
Glad to be of help John. :) I'd also like to know if you find any other scenarios where the above doesn't work, so I can fix my code. Feel free to email me at: [email protected]Nato
I wasn't able to get the code working until I moved the initialisation into the applicationDidFinishLaunching app delegate method, which makes sense given initialize is a class method. Also is there any way to invoke the system crash reporter with the exception instead of just terminating the app?Villalobos
The delegate methods in the example code won't be called since setDelegate:self is called from class method. Either change both delegate methods to class methods as well or move the code to to an instance method where self is the instance and not the classMending
L
1

You can’t reliably. Throwing exceptions across API boundaries is not supported unless explicitly documented (and I can’t think of any cases that are explicitly documented).

Lordly answered 6/9, 2010 at 20:26 Comment(1)
That makes sense. But in that case, how can I catch and report exceptions in my code if HIToolbox keeps catching them before me? Am I right in concluding that I shouldn't be running code from the same thread as an action if I want to catch the exceptions? That seems strange to me. So what's the alternative?Earth

© 2022 - 2024 — McMap. All rights reserved.