Try/Catch for Bronze Challenge


#1

OK, I know you folks (authors) already stated about not usually using Try/Catch blocks in Objective-C. But the Bronze challenge was just too good of an example to try this out on. Here’s my solution and console log when trying to access the eleventh item in the array.

The code, which I added directly after the loop to show all ten array items, but before the call to nil out the items array:

NSLog(@" "); NSLog(@"Attempting to access the 11th item"); @try { NSLog(@"%@", items[10]); } @catch (NSException *exception) { NSLog(@"Failed: %@", [exception reason]); } @finally { NSLog(@"Moving on..."); }

And the resulting log:

... 2014-02-20 10:11:23.801 RandomItems[28219:303] Translucent Bear (1C7U4): Worth $36, recorded on 2014-02-20 18:11:23 +0000 2014-02-20 10:11:23.802 RandomItems[28219:303] Stained Mac (4K8T1): Worth $54, recorded on 2014-02-20 18:11:23 +0000 2014-02-20 10:11:23.802 RandomItems[28219:303] Shiny Bottle (1F0C2): Worth $51, recorded on 2014-02-20 18:11:23 +0000 2014-02-20 10:11:23.802 RandomItems[28219:303] Speckled Spork (3Q9E3): Worth $62, recorded on 2014-02-20 18:11:23 +0000 2014-02-20 10:11:23.811 RandomItems[28219:303] 2014-02-20 10:11:23.812 RandomItems[28219:303] Attempting to access the 11th item 2014-02-20 10:11:23.812 RandomItems[28219:303] Failed: *** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds [0 .. 9] 2014-02-20 10:11:23.813 RandomItems[28219:303] Moving on... Program ended with exit code: 0

Just thought I’d share for anyone else who might be wondering about trying out Try/Catch/Finally syntax.

—> Kelsey McClanahan


#2

Thanks for that! I didn’t know about the [reason], I’ll try it out!