Objective-C中的@try-catch块

为什么@不尝试块工作? 它使应用程序崩溃,但它应该被@try块捕获。

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


@try {
[test characterAtIndex:6];


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

Now I've found the problem.

Removing the obj_exception_throw from my breakpoints solved this. Now it's caught by the @try block and also, NSSetUncaughtExceptionHandler will handle this if a @try block is missing.

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

Objective-C is not Java. In Objective-C exceptions are what they are called. Exceptions! Don’t use them for error handling. It’s not their proposal. Just check the length of the string before using characterAtIndex and everything is fine....