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

为什么@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/

相关文章:

ios - 动态改变UILabel的字体大小

iphone - 如何在 Objective-C 中定义和使用 ENUM?

ios - iOS 7+ 中的 Base64 解码

ios - 等到两个异步 block 被执行后再开始另一个 block

ios - 如何更改 UIButton 标题颜色?

objective-c - Objective-C 中的 NULL 与 nil

objective-c - 项目构建中的 CocoaPods 错误

ios - 尝试将非属性列表对象设置为 NSUserDefaults

ios - 在没有 UITableViewController 的情况下拉取刷新 UITableVi

ios - 从 UIView 到 UIViewController?