Objective-C 中的异常处理
异常处理在 Objective-C 中通过基础类 NSException 提供。
异常处理是通过以下块实现的 −
@try − 此块尝试执行一组语句。
@catch − 此块尝试捕获 try 块中的异常。
@finally − 该块包含一组始终执行的语句。
#import <Foundation/Foundation.h>
int main() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [[NSMutableArray alloc]init];
@try {
NSString *string = [array objectAtIndex:10];
} @catch (NSException *exception) {
NSLog(@"%@ ",exception.name);
NSLog(@"Reason: %@ ",exception.reason);
}
@finally {
NSLog(@"@@finaly Always Executes");
}
[pool drain];
return 0;
}
2013-09-29 14:36:05.547 Answers[809:303] NSRangeException 2013-09-29 14:36:05.548 Answers[809:303] Reason: *** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds for empty array 2013-09-29 14:36:05.548 Answers[809:303] @finally Always Executes
在上面的程序中,程序没有因为异常而终止,而是继续执行后续程序,因为我们使用了异常处理。
objective_c_foundation_framework.html

