Tuesday, November 02, 2004

C++ Exception Handling

I have become convinced that C++ exception handling is designed to empower programmers with the ability to leak memory like there's no tomorrow. A way of ensuring job security, so to speak.

Yes, there are workarounds to avoid leaking objects when throwing and exception, but they require much more work and thinking than simply recognizing an error condition and cleaning up the local objects and returning an error value. Now you can instantly lose track of all your objects and throw yourself into a completely separate area of code without an explicit jump! Hooray for this "power".

Now, with a GC like Java's got, this isn't a big deal. The object just loses a reference and gets cleaned up if it's no longer useful. Not so with C++. The programmer gets all the power he needs to shoot himself repeatedly in the foot with bigger and bigger object leaks.

Symbian has the CleanupStack which is designed to remove references to abandoned objects in the event of an exception, but it is very ugly and unwieldy and frankly not well documented. At least they thought of it, though. The C++ language needs something like this.