繁体   English   中英

@try - 在Objective-C中捕获块

[英]@try - catch block in Objective-C

为什么@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块捕获了,如果缺少@try块, NSSetUncaughtExceptionHandler将处理它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM