Java coders have it easy – crashing constructors

I came across this entry while scanning Java Blogs yesterday about how to handle exceptions within a constructor. The essence of the article is how do you handle the situation where you couldn’t instantiate your object?

So, if the user passes invalid parameters, do you throw an exception? And, slightly more subtly, if your constructor encounters an exception during object setup, how does it handle this?

Interesting article and well worth the read.

But it struck a bit of a chord with me – I recently bought a Nokia N70 phone, and have been cruising the net looking at how you can code for these things. The N70 is a Symbian phone, and while it has J2ME support, the hardcore stuff seems to be done in C++. Now, C++ is an … interesting language, but is not really known for its in-built protection against memory leaks, and when you’re running a program on a device with limited memory, where your app may well run for the order of days or months this suddenly becomes a big deal.

OK, so you just code, really, really carefully. ;)

Well, turns out that constructors are a special case in terms of memory leaks. Symbian doesn’t use standard C++ exceptions, but it does have an analagous concept called “leaving” grafted on. And not being a C++ guru, I couldn’t tell you what difference there is between normal C++ exceptions and the Symbian variety. In any case, the issue when writing Symbian programs appears to be this:

  1. Constructor called
  2. Constructor initialises an instance variable that points to some new object
  3. On the next line, the constructor encounters an error and leaves

So, we now have allocated memory for some new object (step 2 above), but the object that owns it no longer exists – it crashed during construction. And because the object never fully formed, the destructor wasn’t run on it and so couldn’t free up the memory. Ladies and gentlemen, we have memory leak…. :(

Turns out that Symbian programs have an accepted idiom on how to handle this stuff. Objects that can suffer this way have a static construction method (like the whole getInstance() idiom you see in Java). This static constructor creates the object using a constructor that only performs trivial operations that won’t crash, then once the object exists, calls an instance method on the new object that performs 2nd-phase construction. If things turn to jelly, there is at least a concrete object in existence, so the destructor will be called as normal.

Pretty neat. And pretty eye-opening as to the kind of issues you can be exposed to without garbage collection.

(Which is not to say that Java doesn’t have its own issues with memory leaks, but thats a whole other blog post… :) )

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image