发布于 2015-07-05 11:49:03 | 197 次阅读 | 评论: 0 | 来源: 网络整理
异常处理可在 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
在上面的程序,而不是程序终止,由于异常,继续进行后续的程序,因为我们已经使用异常处理。