Objective-Cで例外処理を行う
例外とは、コードが予期しない事態が起きた時に、処理を止めずに進めるための仕組みです。
予想外の入力を受け取った時なども、例外をキャッチすることで、後続の処理へと進めることができます。
たとえば・・・
NSMutableArray *array = [[NSMutableArray alloc] init]; [array insertObject:[[NSNumber alloc] initWithInt:100] atIndex:0]; [array insertObject:[[NSNumber alloc] initWithInt:200] atIndex:1]; [array insertObject:[[NSNumber alloc] initWithInt:300] atIndex:2]; NSLog(@"%d¥n",[[array objectAtIndex:3] intValue]); //例外発生! NSLog(@"例外の後の処理");
3つの要素を持つ配列を用意しました。0〜2までの数値で要素にアクセスすます。
それで、[array objectIndex:3]とやって、(0,1,2)と数えて3番目にアクセスしようとすると・・・
2014-10-07 06:07:03.594 example[964:303] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]' *** First throw call stack:
というNSRangeExceptionという例外が発生しています。
この例外はキャッチされておらず、そのため、例外以後の処理が実行されていません。
以下のような構文で例外をキャッチすることができます。
@try { //例外が発生するところ } @catch (NSException *e) { //例外が発生した時の処理 }
実際にサンプルをみてみます。
NSMutableArray *array = [[NSMutableArray alloc] init]; [array insertObject:[[NSNumber alloc] initWithInt:100] atIndex:0]; [array insertObject:[[NSNumber alloc] initWithInt:200] atIndex:1]; [array insertObject:[[NSNumber alloc] initWithInt:300] atIndex:2]; @try { NSLog(@"%d¥n",[[array objectAtIndex:3] intValue]); //例外発生! } @catch (NSException *e) { NSLog(@"例外が発生しました:%@",e.name); NSLog(@"理由です:%@",e.reason); } NSLog(@"例外の後の処理");
これを実行すると、例外の理由や、例外の名前が@catch以後の処理でちゃんと表示されており、
例外発生後の処理も実行できていることがわかります。
2014-10-07 08:43:24.869 example[1080:303] 例外が発生しました:NSRangeException 2014-10-07 08:43:24.872 example[1080:303] 理由です:*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2] 2014-10-07 08:43:24.873 example[1080:303] 例外の後の処理