iphone - @try - Objective-C 中的 catch block

标签 iphone objective-c try-catch-finally nsexception

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

 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:]: Range or index out of bounds

Char at index 5 cannot be found

Max index is: 3

Finally condition

关于iphone - @try - Objective-C 中的 catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3363612/

相关文章:

java - "finally" block 的功能是什么?

Objective-c Try/Catch 没有捕捉到

iphone - iOS:录音文件格式

ios - 在 UIImage View 中清晰显示 pdf 生成的缩略图

ios - 横向时addChildViewController不起作用

ios - 获取 PHAsset 的 url

iphone - 更改引脚设计

ios - 位置管理器错误 : The operation couldn’t be completed.(kCLErrorDomain 错误 0。)

iphone - 多行 UISegmentedControl

Java finally block 更改类变量的值,但不更改 Try block 中的 return 语句