目录

异常处理(Exception handling)

在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

在上面的程序中,由于我们使用了异常处理,它继续使用后续程序,而不是程序因异常而终止。

↑回到顶部↑
WIKI教程 @2018