@try - Objective-C の catch ブロック 質問する

@try - Objective-C の catch ブロック 質問する

@try ブロックが機能しないのはなぜですか? アプリがクラッシュしましたが、@try ブロックによってキャッチされるはずでした。

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

 @try {
    [test characterAtIndex:6];

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

ベストアンサー1

すべて完璧に動作します:)

 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 です

最後に条件

おすすめ記事