为什么@try 块不起作用?它使应用程序崩溃,但它应该被@try 块捕获。
NSString* test = [NSString stringWithString:@"ss"];
@try {
[test characterAtIndex:6];
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
@finally {
NSLog(@"finally");
}
为什么@try 块不起作用?它使应用程序崩溃,但它应该被@try 块捕获。
NSString* test = [NSString stringWithString:@"ss"];
@try {
[test characterAtIndex:6];
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
@finally {
NSLog(@"finally");
}
一切都很完美:)
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
最后条件
现在我发现了问题。
obj_exception_throw
从我的断点中删除解决了这个问题。现在它被块捕获,并且如果缺少块@try
,NSSetUncaughtExceptionHandler
也会处理这个问题。@try
Objective-C 不是 Java。在 Objective-C 中,异常就是它们的名称。例外!不要将它们用于错误处理。这不是他们的提议。只需在使用 characterAtIndex 之前检查字符串的长度,一切都很好......