throwing an exception in objective-c/cocoa throwing an exception in objective-c/cocoa objective-c objective-c

throwing an exception in objective-c/cocoa


I use [NSException raise:format:] as follows:

[NSException raise:@"Invalid foo value" format:@"foo of %d is invalid", foo];


A word of caution here. In Objective-C, unlike many similar languages, you generally should try to avoid using exceptions for common error situations that may occur in normal operation.

Apple's documentation for Obj-C 2.0 states the following: "Important: Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors (such as a file not being accessible)"

Apple's conceptual Exception handling documentation explains the same, but with more words: "Important: You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime. [.....] Instead of exceptions, error objects (NSError) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications."

The reasons for this is partly to adhere to programming idioms in Objective-C (using return values in simple cases and by-reference parameters (often the NSError class) in more complex cases), partly that throwing and catching exceptions is much more expensive and finally (and perpaps most importantly) that Objective-C exceptions are a thin wrapper around C's setjmp() and longjmp() functions, essentially messing up your careful memory handling, see this explanation.


@throw([NSException exceptionWith…])

Xcode recognizes @throw statements as function exit points, like return statements. Using the @throw syntax avoids erroneous "Control may reach end of non-void function" warnings that you may get from [NSException raise:…].

Also, @throw can be used to throw objects that are not of class NSException.