Your Exceptional Code
As a developer, you know that things don't always go the way you plan. Code that doesn't work like you expect is a never-ending source of joy in your life. Fortunately, Objective-C supplies compiler directives that help you deal with exceptions in blocks of code:
Use @try for code that may throw an exception.
@catch() lets you specify code that gets run when exceptions occur. You can use more than one block if you need to handle different types of exceptions.
You can use @finally if you have code that needs to run whether or not an exception occurred.
Here's an example that uses all three:
NSArray *myArray = [NSArray array]; // an array with no elements @try { // the array is empty, so this will fail: [myArray objectAtIndex:0]; } @catch (NSException *exception) { NSLog(@"name = %@, reason = %@", [exception name], [exception reason]); } @finally { NSLog(@"Glad that's over with..."); }
which will generate the following output in the console log:
name = NSRangeException, reason = *** -[NSCFArray objectAtIndex:]: index (0) beyond bounds (0) Glad that's over with...
If you hadn't caught the exception, your application would have quit and sent the user abruptly to the iPhone's home screen. Catching exceptions is a good thing.
When your code needs to generate an exception, use the NSException class. Suppose you come across a string that's not awesome enough; you could raise an exception like this:
[[NSException exceptionWithName:@"AwesomeException" reason:@"Not awesome enough" ...
Get iPhone App Development: The Missing Manual now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.