01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

210 CHAPTER 10 Error and exception handling<br />

}<br />

}<br />

UIAlertView *av = [[UIAlertView alloc]<br />

initWithTitle:@"Error"<br />

message:message<br />

delegate:nil<br />

cancelButtonTitle:@"OK"<br />

otherButtonTitles:nil];<br />

[av show];<br />

[av release];<br />

Display error<br />

message<br />

You should now have a good fundamental understanding of how to deal with errors in<br />

Cocoa and how to create your own.<br />

10.3 Exceptions<br />

Exceptions play a different role in <strong>Objective</strong>-C and Cocoa than they do in languages<br />

like Java. In Cocoa, exceptions should be used only for programmer errors, and the<br />

program should quit quickly after such an exception is caught. Exceptions should<br />

never be used to report or handle expected errors (like an unreachable host or a file<br />

that can’t be found). Instead, use them to catch programming errors like an argument<br />

being nil that should never be nil or an array having only one item when it’s<br />

expected to have at least two. You get the idea.<br />

So how do you create and throw exceptions?<br />

10.3.1 Throwing exceptions<br />

Exceptions are instances of NSException (or of a subclass thereof). They consist of a<br />

name, a reason, and an optional userInfo dictionary, much like NSError. You can use<br />

any string as an exception name or use one of Cocoa’s predefined names that can be<br />

found at http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/<br />

Exceptions/Concepts/PredefinedExceptions.html.<br />

Exceptions can be thrown either by using the @throw directive or by calling the<br />

raise method on an instance of NSException. The following listing shows an example<br />

of creating and throwing an exception with a predefined exception name.<br />

Listing 10.6<br />

Throwing an exception<br />

if (aRequiredValue == nil) {<br />

@throw [NSException<br />

exceptionWithName:NSInvalidArgumentException<br />

reason:@"aRequiredValue is nil"<br />

userInfo:nil];<br />

}<br />

Uncaught exceptions cause an application to terminate. During development, that<br />

might be just what you want to be alerted that you did something wrong in your program<br />

code or logic. How would you go about catching exceptions, though?

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!