| Article: |
Understanding Exceptions and Handlers in Cocoa | |
| Subject: | Making your programs exception-safe | |
| Date: | 2007-08-07 08:35:37 | |
| From: | DavidPhillipOster | |
|
As the article discusses, exceptions are implemented using the C primitive: longjmp(). Objective-C is not C++. You may have many layers of method call between the code that raises the exception and the method that catches it. It is very easy to write a memory leak.
[factory makePart]throws an exception, the [item release]will never get called and you'll have a memory leak. The usual fix is to get rid of the explicit [item release]and instead create itemwith:
(Note that you don't need the @catchpart.) Written this way, and if doSomeWorkcalls something that throws, you pool will get drained as th stack gets unwound on its way up to the handler.
|
||
Showing messages 1 through 2 of 2.
-
Making your programs exception-safe
2007-08-07 22:39:02 DavidPhillipOster [View]
-
RE: Making your programs exception-safe
2007-08-07 19:12:23 anarakis [View]
Thank you for your kind feedback. I will make sure to include your input in future articles on the NSException class.



is already exception safe. Sure if a raise happens, the [pool release] won't get called, but it turns out that NSAutoreleasePools aren't like other objects: they manage a chain, and when an earlier one NSAutoreleasePool released, it makes sure that all the later ones are cleaned up, too. So, don't bother with @try{}@finally{} guards on your NSAutoreleasePools.
-- David Phillip Oster