在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;
}
执行上面示例代码,得到以下结果 -
2018-11-16 05:01:49.924 main[43936] NSRangeException 
2018-11-16 05:01:49.926 main[43936] Reason: Index 10 is out of range 0 (in 'objectAtIndex:') 
2018-11-16 05:01:49.926 main[43936] @@finaly Always Executes
在上面的程序中,由于使用了异常处理,在执行过程中能够继续运行使用后续程序,而不是程序因异常而终止。
						上一篇:
								Objective_C基础框架
												下一篇:
								Objective-C快速枚举
												
						
						
					
					
					