Handling runtime errors

In this recipe, we will learn how to handle runtime errors within an iOS application.

Getting ready

In this section, we will learn how we can handle runtime errors and learn how we can improve error handling using the @try…@catch…@finally clauses to prevent our application from crashing.

How to do it...

To begin, follow the following simple steps as outlined:

  1. Open the MemoryLeaks.xcodeproj project file.
  2. Open the ViewController.m implementation file from the Project Navigator window.
  3. Modify the viewDidLoad method as shown by the highlighted code sections in the following code snippet:
    - (void)viewDidLoad
    {
       [super viewDidLoad];
      [self causeRuntimeError];
    }
  4. Next, create the causeRuntimeError method as shown in the following code snippet:
    -(void)causeRuntimeError
    {
       NSLog(@"Runtime Error section started");
      NSMutableArray *myArray = [NSMutableArray   
       array];
      for (int x = 0; x < 30; x++) {
        // Add the value to our Array
        [myArray addObject:[NSNumber numberWithInt:x]];
      }
      // This will cause a Runtime error, as we don't have any
      // item at this index within the array.
      [myArray removeObjectAtIndex:30];
      NSLog(@"Runtime Error section completed.");
    }
  5. Then, build and run the application by navigating to Product | Run from the Product menu, or alternatively pressing Command + R.

    You will notice that once the program executes, an exception is raised and the code execution stops. The following screenshot shows the exception error details within the Xcode IDE:

    How to do it...

How it works...

In this recipe, we created a new method causeRuntimeError that allocated an array to hold the maximum capacity of 30 items. We then cycled through the loop and added the integer values from 0 to 29 into this array. Once, all items have been added, the loop exits and we then attempt to remove an item at the 31st position within the array.

Since we don't have an object stored at the 31st position within our array, this results in the code execution halting, causing the exception error information display as shown in the previous screenshot.

Note

If you would like to find out more information on the NSMutableArray class, you can refer to the Apple developer documentation located at the following link:

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSmutableArray_Class/Reference/Reference.html

There's more...

Objective-C provides you with a fail-safe method that can help you handle exception errors that can prevent your application from falling over. Keep in mind, this will still cause an error, but the exception error would have been handled by your application, preventing your app from crashing, and allowing your code to continue executing.

An exception is a special condition that interrupts the normal flow of program execution. There are a variety of reasons why an exception may be generated (exceptions are typically said to be raised or thrown), by hardware as well as software.

Examples include arithmetical errors such as division by zero, calling undefined instructions (such as attempting to invoke an unimplemented method), and attempting to access a collection element out of bounds.

Objective-C exception support involves four compiler directives: @try, @catch, @throw, and @finally, which are explained in the following table:

Objective-C exception handler

Description

@catch

This code block contains exception-handling logic for exceptions thrown in a @try {} block. You can have multiple @catch {} blocks to catch different types of exception.

@throw

This compiler directive allows you to throw an exception, which is essentially an Objective-C object. You typically use an NSException object, but you are not required to use it.

@finally

This code block must be executed whether or not an exception is thrown and is done after the catch statement finishes.

Let's take a look at how we can modify our causeRuntimeError method to take advantage of these compiler directives, and prevent our code from crashing:

  1. Modify the causeRuntimeError method as shown by the highlighted code sections in the following code snippet:
    -(void)causeRuntimeError
    {
       NSLog(@"Runtime Error section started");
      NSMutableArray *myArray = [NSMutableArray 
                      array];
      for (int x = 0; x < 30; x++) {
        // Add the value to our Array
        [myArray addObject:[NSNumber numberWithInt:x]];
      }
      // This will cause a Runtime error, as we don't have any
      // item at this index within the array.
      @try {
        [myArray removeObjectAtIndex:30];
      }
  @catch (NSException *exception) {
        NSLog(@"Error: %@", exception);
      }
      @finally {
        NSLog(@"Runtime Error section completed.");
      }
    }
  2. Next, build and run the application by navigating to Product | Run from the Product menu, or alternatively pressing Command + R.

You will notice that once the program executes, the exception is raised and caught by the @catch code block, and the exception error message is logged to the console window, and the code execution continues normally.

Note

If you would like to find out more information on Objective-C exception handling, you can refer to the Apple developer documentation located at the following link:

https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocExceptionHandling.html

See also

  • The Running and profiling an iOS project recipe
  • The Building the user interface for our application recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset