Alex Michaud
Alex Michaud

Reputation: 428

My Objective-C exceptions don't cause my app to terminate, but Apple's do

In my iOS (iPhone/cocos2d) project, I'm finding that exceptions I throw myself aren't causing the app to terminate (they just cause the current function to exit, which leads to weird half-frozen behavior). For example, the following code causes a crash:

NSArray* testArray = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
[testArray objectAtIndex:400];

When I run that code, I get the following in the console, as I would expect:

2011-06-07 12:55:20.421 mansion-iphone[38184:207] *** Terminating app due to
    uncaught exception 'NSRangeException', reason: '*** -[NSArray
    objectAtIndex:]: index 400 beyond bounds [0 .. 2]'

However, if I try to raise an exception (e.g. from an assert), I get the half-freeze unless I've enabled "Stop on Objective-C exceptions". This is fine for me but causes problems when my testers report problems -- since the app didn't crash, they don't have a crash log to send me. Here's an example of an exception that doesn't work:

NSException* e = [NSException exceptionWithName:NSInternalInconsistencyException 
        reason:[NSString stringWithFormat:@"%s %@", __PRETTY_FUNCTION__,
        [NSString stringWithFormat:@"Invalid argument"]] userInfo:nil];
[e raise];

With "Stop on Objective-C exceptions" turned off, that doesn't even cause a message to the console -- using NSAssert instead gives me a console message but still no stop. So, it seems like exceptions generated by Cocoa classes are behaving correctly, but exceptions originated from my code aren't.

I've checked my code and cocos2d and haven't found any @try blocks that would seem to prevent an exception; anybody have an idea?

Upvotes: 1

Views: 1016

Answers (1)

Stuart Carnie
Stuart Carnie

Reputation: 5476

A custom exception should work the same as other exceptions, and I was able to verify this in my own test application. Some things to check:

  1. Make sure NSSetUnhandledExceptionHandler is not being called, to catch all unhandled exceptions.
  2. Try running your app outside the debugger.
    • I tested your code above, and my application terminates as expected when either NSRangeException or the custom NSException is raised and not handled.
  3. Try raising your exception elsewhere to verify it is working, such as main().

NOTE: Do not use exceptions as a way to control program flow, as they are very expensive when raised in Objective-C.

Upvotes: 5

Related Questions