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.htm
广告
© . All rights reserved.