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:

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.

Definitive Discussion

Prerequisite Articles

    (None)

Related Articles

    (None)

Did this document help you? Yes It's good, but... Not helpful...


Last updated: 2010-08-03