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;
}

執行上面示例代碼,得到以下結果 -

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快速枚舉