2010-06-10 60 views
1

实施例:try块内发生了什么?

@try { 
    // 1) do bad stuff that can throw an exception... 

    // 2) do some more stuff 

    // 3) ...and more... 
} 
@catch (NSException *e) { 
    NSLog(@"Error: %@: %@", [e name], [e reason]); 
} 

如果1)抛出异常,是立即取消像在一个函数在一个循环中返回或断裂块?或者将2)和3)无论发生在1)中都发生了什么?

回答

4

如果发生异常,则立即执行块中断,并执行@catch节(如果它处理了适当的异常类型)。

示例代码:

@try { 
    NSArray* arr = [NSArray arrayWithObjects:@"1", @"2", @"3", nil]; 
    NSLog([arr objectAtIndex: 0]); 
    NSLog([arr objectAtIndex: 5]); 
    NSLog(@"Lala"); 
} 
@catch (NSException * e) { 
    NSLog(@"%@, %@", [e name], [e reason]); 
} 

Output: 
1 
NSRangeException, *** -[NSCFArray objectAtIndex:]: index (5) beyond bounds (3)