Exception handling

Exception handling is the process of managing atypical events (such as unrecognized messages) that interrupt the normal flow of program execution. Without adequate error handling, a program that encounters an atypical event will most likely terminate by immediately throwing (or raising) what’s known as an exception.

Types of Exception

There are a variety of reasons why an exception may be thrown, by hardware as well as software. Examples include arithmetical errors such as division by zero, underflow or overflow, calling undefined instructions (such as attempting to invoke an unimplemented method), and attempting to access a collection element out of bounds.

Handling Exceptions Using Compiler Directives

There are four compiler directives to support exception handling:

  • A @try block encloses code that can potentially throw an exception.

  • A @catch() block contains exception-handling logic for exceptions thrown in a @try block. You can have multiple @catch() blocks to catch different types of exception.

  • A @finally block contains code that must be executed whether an exception is thrown or not.

  • A @throw directive raises an exception, which is essentially an Objective-C object. You typically use an NSException object, but are not required to.

This example shows how you use the directives when executing code that might raise an exception:

Cup *cup = [[Cup alloc] init];
 
@try {
    [cup fill];
}
@catch (NSException *exception) {
    NSLog(@"main: Caught %@: %@", [exception name], [exception  reason]);
}
@finally {
    [cup release];
}

Signaling Errors

Although exceptions are commonly used in many programming environments to control programming flow or to signify errors, do not use exceptions in this way in Cocoa and Cocoa Touch applications. Instead, you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object. For more information, see Error Handling Programming Guide.

Prerequisite Articles

    (None)

Related Articles

    (None)

Definitive Discussion