@try - Objective-C 中的 catch 块

发布于 2024-09-11 19:44:57 字数 269 浏览 24 评论 0原文

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

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

 @try {
    [test characterAtIndex:6];

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

兔姬 2024-09-18 19:44:57

一切工作都很完美:)

 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

最终条件

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

爱殇璃 2024-09-18 19:44:57

现在我发现了问题所在。

从我的断点中删除 obj_exception_throw 解决了这个问题。现在它被 @try 块捕获,并且如果 @try 块丢失,NSSetUncaughtExceptionHandler 将处理这个问题。

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.

天暗了我发光 2024-09-18 19:44:57

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

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....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文