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.

Search your source code for methods that are not setters, and are not -(void)dealloc but which call -(void)release.

A common pattern is:

MyItem *item = [[MyItem alloc] init];
[item setPart:[factory makePart]];
[myArray addObject:alteredItem];
[item release];

Now, if

[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

MyItem *item = [[[MyItem alloc] init] autorelease];

But that doesn't work for autorelease pools. If you are creating autorelease pools, and something you write might call something that might someday be maintained to throw exceptions, you must write not the usual:

NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
[self doSomeWork];
[NSAutoReleasePool release];

but instead the correct:

@try {
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
[self doSomeWork];
[NSAutoReleasePool release];

(Note that you don't need the
Written this way, and if
calls something that throws, you pool will get drained as th stack gets unwound on its way up to the handler.

Lastly, If you are writing in Objective-C++, be aware that C++ exceptions and Objective-C exceptions don't mix. If your program might ever be maintained to throw either kind, then, at the points where the program switches from one language to the other, it must catch the inner exception in one language, and rethrow it as the equivalent exception in the other language. (And note as the stack is unwound the exception may be rethrown from C++ to Objective-C and back multiple times.)

Note that ANY use of [XXX alloc] could, in theory, throw a NSMallocException, and be very afraid.

Are all your programs NSException safe?

1 to 2 of 2
  1. Making your programs exception-safe
    2007-08-07 22:39:02  DavidPhillipOster [View]

  2. RE: Making your programs exception-safe
    2007-08-07 19:12:23  anarakis [View]

1 to 2 of 2