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.
Throwing and catching exceptions in Objective-C is expensive (except on 32-bit Mac OS X, where the
@trypart of the exception-catching code is the expensive part instead of the@catchpart.)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
NSErrororNSExceptionobjects 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.)