Objective-C语言使用try catch块进行错误和异常处理

示例

异常表示程序员级别的错误,例如尝试访问不存在的数组元素。

错误是用户级别的问题,例如尝试加载不存在的文件。因为在程序正常执行期间会出现错误。

示例

    NSArray *inventory = @[@"Sam",
                           @"John",
                           @"Sanju"];
    int selectedIndex = 3;
    @try {
        NSString * name = inventory[selectedIndex];
        NSLog(@"The selected Name is: %@", name);
    } @catch(NSException *theException) {
        NSLog(@"An exception occurred: %@", theException.name);
        NSLog(@"Here are some details: %@", theException.reason);
    } @finally {
        NSLog(@"Executing finally block");
    }

输出:

发生异常:NSRangeException

以下是一些详细信息:***-[__ NSArrayI objectAtIndex:]:索引3超出范围[0 .. 2]

执行最终阻止