allenlinli allenlinli - 29 days ago 10
iOS Question

Why does "try catch" in Objective-C cause memory leak?

I am thinking about pros and cons of Try-Catch in Objective-C.
According to this article Dispelling NSException Myths in iOS: Can We Use @try…@catch, @finally?, try-catch isn't that bad, except for it leaks memory in ARC.

So how does try-catch cause memory leak?

Answer

First of all: Exceptions have different semantics in Objective-C. An exception means that something went completely wrong because of a programming mistake and the further execution of the application is not useful. Terminate it. To handle "expected errors" (like insufficient user input or not responding servers et al.) use Cocoa's error handling pattern. (The reason for this is that exceptions seems to be convenient in many situation, but are very hard to handle in other situations, i. e. while object construction. Read about exceptions in a C++ book and feel the pain.)

To your Q: ARC adds additional code to handle memory management. This code has to be executed to handle the memory management, esp. to release objects. If an exception occurs before this is done, the control flow never reaches the release statement. Memory leaks.

- (void)method
{
   id reference = …;
   // Some ARC code to retain the object, reference points to.
   … // Throws an exception
   // reference loses its extent.
   // Some ARC code to release the object, reference points to.
}

If you have an exception at , the method is left immediately and the ARC code to release the object is never executed. This is the leak.

You can change this behavior by compiling the source with -fobjc-arc-exceptions option.

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#exceptions

This will add additionally code to make ARC exception-safe with a runtime penalty. But there is little reason to do so in Cocoa development because … Yes, read the beginning of this answer.