Objective-C 中的异常处理
异常处理在 Objective-C 中与基础类 NSException 一起提供。
异常处理通过以下块实现:
#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;}
结果如下:
2022-07-07 16:36:05.547 Answers[809:303] NSRangeException2022-07-07 16:36:05.548 Answers[809:303] Reason: *** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds for empty array2022-07-07 16:36:05.548 Answers[809:303] @finally Always Executes
在上面的程序中,由于我们使用了异常处理,程序不会因异常而终止,而是继续执行后续程序。