Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 942
allenlinli Avatar asked Nov 26 '14 03:11

allenlinli


1 Answers

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 C++. It is painful.)

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.
   … 
   @throw …
   …
   // reference loses its extent, because of method termination
   // Some ARC code to release the object, reference points to.
}

If you have an exception, the method is left immediately and the ARC code and the end of the method 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 code to make ARC exception-safe causing a runtime penalty. But there is little reason to do so in Cocoa development, as explained at the beginning of this answer.

like image 90
Amin Negm-Awad Avatar answered Sep 20 '22 15:09

Amin Negm-Awad