Objective-c-exception-handling

提供:Dev Guides
移動先:案内検索

Objective-Cでの例外処理

例外処理は、Foundation-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

上記のプログラムでは、例外のためにプログラムが終了する代わりに、例外処理を使用しているため、後続のプログラムを継続します。