Take the 2-minute tour ×

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:


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?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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!

share|improve this answer
add comment

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.

share|improve this answer
I tried that and I'm still not catching the exception. -reportException: never gets called. If the exception was raised in -applicationDidFinishLaunching:, shouldn't it be called? Isn't that run on the main thread? –  edc1591 Mar 21 '12 at 12:10
Yes, -applicationDidFinishLaunching: is called on the main thread. Are you sure your NSApplication subclass is being used? You need to specify its class name in your Info.plist under the key NSPrincipalClass. –  Kurt Revis Mar 21 '12 at 17:37
Yes, I am sure. [NSApp class]; returns my subclass. –  edc1591 Mar 21 '12 at 18:53
I've also tried using ExceptionHandling.framework, but the delegate methods don't get called. –  edc1591 Mar 21 '12 at 19:11
Hmmm, I'm out of ideas, then. I'd set a breakpoint on NSLog and see what code is logging the exception message -- the backtrace might tell you where the exception is getting caught. –  Kurt Revis Mar 21 '12 at 20:41
show 1 more comment

Your Answer


