Tuesday, May 29, 2012

how to throw an exception in objective-c/cocoa?


what's the best way to throw an exception in objective-c/cocoa?



Source: Tips4all

9 comments:

  1. I use [NSException raise:] as follows:

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

    ReplyDelete
  2. 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.

    ReplyDelete
  3. I don't have the rep to comment on eJames' response, so I guess I need to put mine here. For those coming from a Java background, you will recall that Java distinguishes between Exception and RuntimeException. Exception is a checked exception, and RuntimeException is unchecked. In particular, Java suggests using checked exceptions for "normal error conditions" and unchecked exceptions for "runtime errors caused by a programmer error." It seems that Objective-C exceptions should be used in the same places you would use an unchecked exception, and error code return values or NSError values are preferred in places where you would use a checked exception.

    ReplyDelete
  4. @throw([NSException exceptionWith…])

    ReplyDelete
  5. I think to be consistant it's nicer to use @throw with your own class that extends NSException. Then you use the same notations for try catch finally:

    @try {
    .....
    }
    @catch{
    ...
    }
    @finally{
    ...
    }


    Apple explains here how to throw and handle exceptions:
    Catching Exceptions
    Throwing Exceptions

    ReplyDelete
  6. Since ObjC 2.0, Objective-C exceptions are no longer a wrapper for C's setjmp() longjmp(), and are compatible with C++ exception, the @try is "free of charge", but throwing and catching exceptions is way more expensive.

    Anyway, assertions (using NSAssert and NSCAssert macro family) throw NSException, and that sane to use them as Ries states.

    ReplyDelete
  7. I believe you should never use Exceptions to control normal program flow. But exception shold be trown whenever some value doesn't match a desired value.

    For example if some function accepts a value, and that value is never allowed to be nil, then it's fine to trow an exception rather then trying to do something 'smart'...

    Ries

    ReplyDelete
  8. Use NSError to communicate failures rather than exceptions.

    Quick points about NSError:


    NSError allows for C style error codes (integers) to clearly identify the root cause and hopefully allow the error handler to overcome the error. You can wrap error codes from C libraries like SQLite in NSError instances very easily.
    NSError also has the benefit of being an object and offers a way to describe the error in more detail with its userInfo dictionary member.
    But best of all, NSError CANNOT be thrown so it encourages a more proactive approach to error handling, in contrast to other languages which simply throw the hot potato further and further up the call stack at which point it can only be reported to the user and not handled in any meaningful way (not if you believe in following OOP's biggest tenet of information hiding that is).


    Reference Link: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nserror_Class/Reference/Reference.html

    ReplyDelete
  9. There is no reason not to use exceptions normally in objective C even to signify business rule exceptions. Apple can say use NSError who cares. Obj C has been around a long time and at one time ALL C++ documentation said the same thing. The reason it doesnt matter how expensive throwing and catching an exception is, is the lifetime of an exception is exceedingly short and...its an EXCEPTION to the normal flow. I have never heard anyone say ever in my life, man that exception took a long time to be thrown and caught.

    Also, there are people that think that objective C itself is too expensive and code in C or C++ instead. So saying always use NSError is ill-informed and paranoid.

    But the question of this thread hasnt yet been answered whats the BEST way to throw an exception. The ways to return NSError are obvious.

    So is it: [NSException raise:... @throw [[NSException alloc] initWithName....
    or @throw [[MyCustomException... ?

    I use the checked/unchecked rule here slightly differently than above.

    The real difference between the (using the java metaphor here) checked/unchecked is important --> whether you can recover from the exception. And by recover I mean not just NOT crash.

    So I use custom exception classes with @throw for recoverable exceptions, because
    its likely I will have some app method looking for certain types of failures in multiple
    @catch blocks. For example if my app is an ATM machine, I would have a @catch block for the
    "WithdrawalRequestExceedsBalanceException".

    I use NSException:raise for runtime exceptions since I have no way to recover from the exception,
    except to catch it at a higher level and log it. And theres no point in creating a custom class for that.

    Anyway thats what I do, but if there's a better, similarly expressive way I would like to know as well. In my own code, since I stopped coding C a hella long time ago I never return an NSError even if I am passed one by an API.

    ReplyDelete