197

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

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

 @try {
    [test characterAtIndex:6];

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

3 回答 3

144

一切都很完美:)

 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");
 }

日志:

[__NSCFConstantString characterAtIndex:]:范围或索引超出范围

找不到索引 5 处的字符

最大指数为:3

最后条件

于 2012-11-29T02:23:59.307 回答
78

现在我发现了问题。

obj_exception_throw从我的断点中删除解决了这个问题。现在它被块捕获,并且如果缺少块@tryNSSetUncaughtExceptionHandler也会处理这个问题。@try

于 2010-07-30T08:47:08.947 回答
0

Objective-C 不是 Java。在 Objective-C 中,异常就是它们的名称。例外!不要将它们用于错误处理。这不是他们的提议。只需在使用 characterAtIndex 之前检查字符串的长度,一切都很好......

于 2018-11-15T15:35:39.677 回答