How to Handle Exceptions in Objective-C in iOS Apps - dummies

How to Handle Exceptions in Objective-C in iOS Apps

By Rajiv Ramnath

In Objective-C, exceptions deal with unexpected conditions in your program. Consider the following when creating code so as to prevent failures within your iOS apps. Pay close attention to:

  • An alloc statement fails because your system runs out of memory.

  • Bad input gets into your program causing (say) a divide-by-zero error.

  • Your program erroneously tries to access an array with an index that’s out of bounds.

Exceptions apply the Object Oriented principle of separation of concerns which is the idea of dividing an application into distinct components that overlap in functionality as little as possible. The value of separation of concerns is simplifying development and maintenance of computer programs.

When concerns are well separated, individual sections can be developed and updated independently. Exceptions also automate the propagation of an unexpected condition to the point where it’s handled. As a result, your code isn’t cluttered with exception-handling statements, which makes your code easier to write and maintain.

Objective-C extends C by providing four compiler directives for exception handling:

  • @try defines an exception handling block (that is, code that could throw an exception).

  • @catch() defines a block of code for handling the exception thrown in the @try block. The parameter of @catch is the exception object thrown; this is usually an NSException object.

  • @finally defines a block of code that’s executed whether or not an exception is thrown.

  • @throw throws an exception — an NSException object or, more often, an object belonging to a subclass of NSException.

The following code shows how exceptions can be thrown, caught, and handled within a @try…@catch block.

@try {
  printf("I know this will failn");
  NSDictionary* emptyDictionary = [[NSDictionary alloc] init];
  NSException* anException =
   [NSException exceptionWithName:@"MyException" reason:@"Just for grins" userInfo:emptyDictionary];
  @throw anException;
 @catch (NSException *exception) {
  NSLog(@"Exception caught with reason >%@<n", exception);