位置:首页 » 文章/教程分享 » 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 

在上面的程序,而不是程序终止,由于异常,继续进行后续的程序,因为我们已经使用异常处理。