While in Objective-C, it is much less powerful and shouldn't rely on it, as usually it just crash and didn't catch anything. Yet, it is still a plus if you really catch something.
Usage is really simple
@try { Function_You_Want_To_Catch_Exception; } @catch (NSException* exception) { Do_Thing_After_Exception_Caught; }
One example is to put it in
main.m
, in order to catch any uncaught exception.which shows how to catch all uncatched exception in the app.int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = -1; @try { retVal = UIApplicationMain(argc, argv, nil, nil); } @catch (NSException* exception) { NSLog(@"Uncaught exception: %@", exception.description); NSLog(@"Stack trace: %@", [exception callStackSymbols]); } [pool release]; return retVal; }
Another usage is when you like "exception programming", you can raise your own exception, by using [NSException raise:format:] and catch it with above code.
Example:
[NSException raise:NSInvalidArgumentException format:@"Foo must not be nil"];
There are several exception name already defined by apple here. but if you want to use your own, put a NSString there is fine.
沒有留言:
張貼留言