Exception handling in Objective-C



Exception handling is made available in Objective-C with foundation class NSException.

Exception handling is implemented with the following blocks −

  • @try − This block tries to execute a set of statements.

  • @catch − This block tries to catch the exception in try block.

  • @finally − This block contains set of statements that always execute.

#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

In the above program, instead of the program terminating due to the exception, it continues with the subsequent program since we have used exception handling.

objective_c_foundation_framework.htm
Advertisements