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
廣告