@try - catch block in Objective-C

Alexandru Circus picture Alexandru Circus · Jul 29, 2010 · Viewed 150.3k times · Source

Why doesn't @try block work? It crashed the app, but it was supposed to be caught by the @try block.

 NSString* test = [NSString stringWithString:@"ss"];

 @try {
    [test characterAtIndex:6];

 }
 @catch (NSException * e) {
    NSLog(@"Exception: %@", e);
 }
 @finally {
    NSLog(@"finally");
 }

Answer

iTux picture iTux · Nov 29, 2012

All work perfectly :)

 NSString *test = @"test";
 unichar a;
 int index = 5;
    
 @try {
    a = [test characterAtIndex:index];
 }
 @catch (NSException *exception) {
    NSLog(@"%@", exception.reason);
    NSLog(@"Char at index %d cannot be found", index);
    NSLog(@"Max index is: %lu", [test length] - 1);
 }
 @finally {
    NSLog(@"Finally condition");
 }

Log:

[__NSCFConstantString characterAtIndex:]: Range or index out of bounds

Char at index 5 cannot be found

Max index is: 3

Finally condition