Home → 2003/10/23, 22h29

Joel on exceptions

Joel Spolsky writes about exceptions. That reminds me of the first commercial app I worked on back in 1993 (ouch... 10 years ago!)

This was a cutting edge app fully written in Object Oriented C++, based on the Windows 3.1 APIs. This was a huge app that took something like an hour to build and link (maybe more, not sure). There were no exceptions in there. Almost every class was written following a "policy" that sounded roughly like this:

  • Never let the app cause a GPF.
  • Always return something from every method. Instead of void, return "boolean".
  • Always check the return value of a method before calling the next.
  • exit "gracefully"

So the code looked like this (I am not kidding):


  BOOL bRet = TRUE;
  bRet = bRet && memDCsrc.CreateCompatibleDC( &dc );
  bRet = bRet && memDCdst.CreateCompatibleDC( &dc );
  CBitmap NewBitmap;
  bRet = bRet && NewBitmap.CreateCompatibleBitmap(
                          dc,
                          rcDst->right - rcDst->left,
                          rcDst->bottom - rcDst->top );

I remember that I used to scroll my editor window so it would hide the bRets. That way, I could see the juice of the program.

If you put this in a call stack of similarly implemented methods, and if a function returns false, you get out of the stack while loosing the context where the error occurred. At that time, I tried to argue against this tedious method but being new in this programming area, I had trouble finding good arguments (not that I am better at arguing today though.) To me, this approach is similar to


  try{
    memDCsrc.CreateCompatibleDC( dc );
    memDCdst.CreateCompatibleDC( dc );
    CBitmap newBitmap = 
       CBitmap.CreateCompatibleBitmap(
                              dc,
                              rcDst.ight - rcDst.left,
                              rcDst.bottom - rcDst.top );
} catch(Exception e){
  throw new Exception();
}

which is a pretty bad way to deal with exceptions (I will not get into the "whys" but at least, the thrown exception should be instantiated like this: new Exception(e).) Anyway, in the bRet code, you would typically check that you get true at the top of the stack, and this is practically similar to catching the exception at the top.

I do not know whether or not exceptions are better than error codes. But I do know that it is important to identify errors and take care of them before they reach users. And if we can store with the error some context information like a call stack, things are even better.

Exceptions in Java give us context information for free.