Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Wednesday, June 25, 2008

To release or not to release? autorelease duh!

Well, it turns out that the standard class methods used to instantiate a new NSException object, send an autorelease message to the object, effectively putting it on the nearest NSAutoreleasePool. As with my earlier issue with the cost of the try/catch block, I was mis-informed :-| ... mind you, I have yet to see any official document clearly stating the memory whereabouts of an exception ...

To release or not to release?

Since exceptions in Objective-C are full featured objects (which don't have to be derived from NSException), it is legit for a code monkey to wonder when are the exceptions ... well you know, released. From what I have seen so far in Apple documents and from (most) code samples I see on the web, it appears as exception object are released automagically at some point ... but are they really? Having derived Cocoa's exception class to add an origin field to it, I also added to my class an implementation of the dealloc method (so that I could release the origin string). For good measure, I also added a printf statement just to verify that the method was been called (e.g I could have goofed up the signature).

As you will have guessed (easy since otherwise I will not be blogging about it), I found out that the method was not been called unless I explicitly send a release or autorelease message to the exception object within the catch block ... (!!?) A quick search on the web didn't yield more details, except for an blog post by Chris Hanson showing an autorelease message been sent from a finally block for a caught exception (however that occurrence is due to him retaining the exception in the catch block, so not really relevant to the case at hand). I'll have to dig this further ...

Tuesday, June 24, 2008

NSObject+CleanupAwareness

To the risk of boring to death my single reader (sorry Usman!), let's continue a bit on the subject of exception :-P Thanks to Objective-C support for categories, it is possible to add shortcut methods to the ubiquitous NSObject class, so that any instantiation of a derived class (virtually any classes of Cocoa) can push and pop itself on/from an existing cleanup stack. And how do we get around of doing that you may ask? Well simply by creating a category of the class:
@interface NSObject (CleanupAwareness)

- (void) pushForCleanupL;

- (void) popFromCleanupL;

@end
The implementing it as follow:
@implementation NSObject (CleanupAwareness)

- (void) pushForCleanupL {

[[HZCleanupStack current] pushL:self];

}

- (void) popFromCleanupL {

[[HZCleanupStack current] popL:self];

}

@end
Then Objective-C will work its magic and any code linked to yours will have it's objects capable of being placed on our cleanup stack. Cool stuff isn't it? At first I wasn't too much excited by Objective-C (its syntax was a little odd for a C++ monkey like myself), but it have definitely grow on me as I got to known it better :-)

If you are, like myself, dying to see the next Pixar movie (this Friday!), be sure to read the review written by (darn) lucky Scott Stevenson on his blog. While you are had it, you may want to also read all the good material that he have written about Cocoa & Objective-C on Cocoa Dev Central.

Sunday, June 22, 2008

Tidying things up a bit ...

The second thing I have been carrying over from Symbian is a mechanism that goes hand-in-hand with exceptions, the (infamous among beginners) cleanup stack. Its purpose is quite simple: insure that no memory will be leaked when exception occurs. In an environment where exceptions are used pervasively (like Symbian), the interruption of the natural flow of execution can easily lead to temporary objects allocated on the heap been orphaned, each constituting a memory leak. The idea behind the cleanup stack (Symbian's style) , is to allow (and actually enforce) programmers to push object on a special stack prior to any call that could throw an exception, or to use the standard Symbian lingo: leave. Once the call has been completed, the object must be popped from the special stack. This sounds like extra work for the developer isn't it? Well, yeah it is a bit more work and a bit more careful thinking, but it is well worth the trouble when the application must run for long period of time on an system where resources are spare (iPhone anyone?).

Originally (well, last week actually ...) I had implemented my cleanup stack as a set of C functions to be called from within a try/catch block. The problem is that thanks to the lack of namespace and functions overloading in C, my functions had the severe tendency to be ultra long. Now, I know about Apple's mantra: "developer spend more times reading than writing code", but still who'll like to have to type this function call hundreds of times per file (yeah , OK I exaggerate a bit about the occurence of such call ...):
HZCleanupStackPopAndReleaseManyWithLastObjectL(...);
So yesterday I started re-implementing my stack as an Objective-C class which allow for more developer friendly code to be written, at the cost of a bit more overhead since messages are to be sent to the stack instead of more efficient function calls. Now, in case you did not follow one of the first page referenced on this post (actually the second one), allow me qto uickly show how the cleanup stack is been used. Let's assume that you need to call a function that is known to leave (following Symbian coding style, the function/method name must be post fixed with an upper case L): doSomeL(). As an experienced developer, you know that you must call this function from within a try/catch block or from another function that is also known to throw exception. In this case, we will use a try/catch block. Your function will be looking somewhat like this:
void doTest()
{
@try {

[HZCleanupStack windUpL];

doSomeL();

} @catch(NSException* lException) {

printf("exception occured\n");

} @finally {

[HZCleanupStack unwind];

}
}

It's contents is simple: at the start of the try block, the cleanup stack is winded-up (created) then the function is called. When the try/catch block end, the stack is un-winded (destroyed). If an object was created (and placed on the cleanup stack) in the doSomeL() function before it threw an exception, the un-winding of the stack in the finally block will release it, serving the purpose it was built for. Let's now have a look at an example of a toublesome function:
void doSomeL()
{
HZObject* lObject[2];
HZReleaseStack* lStack = [HZCleanupStack current];

lObject[0] = [HZObject newLC];
lObject[1] = [HZObject newLC];

someFunctionL(false,lObject[1]);

[lStack popAndReleaseManyL:2 withLast:lObject[0]];
}

Here, we will assume that we have an class of object (HZObject) which will accept the selector newLC as a way of instantiating objects. The post fix LC indicates that the call can throw an exception and that otherwise it will leave the created instance on the cleanup stack. Since the function is known to potentially leave, it is assumed that it have been called from within a try/catch block, thus a cleanup stack is available, the selector current used on the class HZCleanupStack will return it to us (in fact, it will return the last winded stack for the calling thread) so that we can pop the two allocated objects. Now, what happens if this function isn't called from within a try/catch block? Well, the creation of the first object will throw an exception and the object it-self will be released.

If that help, I should maybe mention that the cleanup stack concept is somewhat a kin to a NSAutoreleasePool object with the added ability to push then pop objects at will. Maybe I'll add to this in a following post.

Wednesday, June 18, 2008

Zero-cost exception! (No, really).

Following up on my post from this morning, it turned out that my hunch was correct. GCC on 64-bit MacOS X, require the -m64 flag to compile x64 code. Once I added it, the try/catch block really did become zero-cost. Problem solved (now what about on the iPhone?) ... as advertised by Apple release note :-)

Zero-cost exception?

Like any code monkey that have been around for a while, I have assembled from my various experiences (BeOS, QNX, Symbian, Win32 ...) a particular coding style and set of paradigms/concepts I like to use for my own projects. When I start on a new platform, I usually have to adapt my style to what is available and/or most commonly used on the platform, and this is usually a good exercise that goes hand-in-hand with learning a new environment. Since I have picked-up the usage of exception for error handling from my mobile development days at Nokia, this is one of the first thing I have been looking at when starting with Objective-C. Now, I'm not going, in this blog, to join the on-going debate raging in the software community about the pros&cons of using exceptions vs. returning error codes, however I should state that I do prefers to use exceptions as they allow for a more elegant and clean (meaning readable) code (IMHO).

After finding a couple of references (can't find the link now) to the fact that Objective-C's exception handling is not as efficient as C++ (meaning not zero-cost), I decided that I should try to check that out. For that purpose I wrote a simple (and naive) test program which measure the elapsed time for a loop calling a function containing either a try/catch block or a old fashion if statement. Here is the function been called repeatedly:
void loop(Foo* aFoo)
{
static int i=0;
#ifdef _EXCEPTION
@try {
[aFoo doSomeL:i++];
} @catch(NSException* lException) {
printf("An exception was thrown!\n");
} @finally {
}
#else
if([aFoo doSome:i++] == NO)
printf("An error occured!\n");
#endif
}
The Foo object here used is of no real importance. In both path the message been sent will compare the value passed as argument and will return an error or throw an exception when an hard-coded value is reached within the loop. Since my immediate concern was the cost of try/catch block, I had set the hard-coded value to be higher than the loop range so that even if the test was been performed at each loop, it will not trigger an error or exception.

I was rather disappointed when I ran the program with if statement then with the try/catch block and noted than the later was 8.2 times slower (without any exception been throw). Since my understanding was that Objective-C's exception handling on 64-bit had been improved compared to 32-bit with 10.5 (see bottom of release notes), I'm definitely surprised considering that I was testing this on an iMac (Intel Core Duo 2, gcc 4.0). Now, it is possible that I'm doing something wrong ... I'll have to double check that I was indeed compiling for 64-bit, which I assumed was the case since I believe that gcc will use this mode per default on a 64-bit machine (at least that's the way it work on Linux).

Since I have easy access to a x64 Linux box (gcc 4.1 with Objective-C support), I quickly adapted my test to the absence of Cocoa and noted with than the cost of the try/catch block was only 1.03 times higher than an if statement ... evidently zero-cost as advertised. So what it's going on with OS-X?