views:

71

answers:

4

I'm converting a Java library to Objective-C. The Java code uses exceptions flagrantly (to my Objective-C accustomed mind). When converting, should I be throwing Objective-C exceptions (only within the library; I'll catch them before they leave) or should I use NSError constructs.

I'm familiar with the use-case for exceptions in regular Objective-C code; i.e. only for truly exceptional errors. If I don't get a definitive answer here, I'll probably use NSErrors.

+1  A: 

I would just return errors on the Objective-C library (NSError approach). After all, it's the way error handling is done in C.

Pablo Santa Cruz
+2  A: 

If the library can handle all the exceptions on its own, then they're not really exceptions in the Objective-C sense of the word: no programmer error has occurred; rather, something wholly anticipated has happened. You should use use error codes/NSError as needed, but you might be able to dispose with much of the info provided by the exceptions and just return a value that indicates an "error" (nil, 0, and NSNotFound being some of the common ones) and handle that. You might also consider error-handling delegate methods.

Jeremy W. Sherman
+2  A: 

Throwing and catching exceptions in Objective-C is expensive (except on 32-bit Mac OS X, where the @try part of the exception-catching code is the expensive part instead of the @catch part.)

You're better off returning error codes in some mechanism (such as NSError, the OO way to do it in Objective-C.) Let those bubble up to the code that accesses your framework, and then let that code handle it appropriately.

Memory cleanup in the case of error with either system should not be a huge worry, as you should be able to put most objects and allocations in an autorelease pool. However, be advised that the pool will eat up any NSError or NSException objects created within its scope, so you'll have to make sure those objects survive past the end of your code with additional retains and releases. (Slightly off-topic, but I've seen a lot of people screw this part up when doing error handling.)

Jonathan Grynspan
Thanks to everybody who answered.
CajunLuke
+1  A: 

I wouldn't worry too much about using or not using exceptions. If it makes your code cleaner, use them. The only thing you really have to be careful about is not throwing exceptions through code that you do not know is exception safe which is pretty much all code you did not write.

Yes, using exceptions is expensive, but worrying about that is an example of premature optimisation. After all, compared with a C function call, Objective-C message dispatch is expensive, but you don't hear Objective-C programmers saying "don't use Objective-C messages".

JeremyP