Checking function return values

A lot of you are guilty of not checking return values from API function calls. I’ll bet you have a good excuse, like “it’s a lot of extra typing for no reason”, or “that function should never return an error code”.

I check return values religiously, use asserts liberally, and never assume that the implementation details of a function won’t change in the future. I think you should do the same.

In all my years of programming, I’ve never heard someone complain that their project failed because they spent too much extra time typing code to verify return values — but I have heard of projects failing because sloppy code made it almost impossible to diagnose and fix problems.

I see a lot of “sample code” posted on the internet in forums and blogs that omit error checking for brevity or to make the code clearer to read. That’s a bad idea, in my opinion. Sample code should be good code, not just clean code.

I will grant you that there are cases where error checking is not needed. For example, in the following code there is no need to verify the result of the call to acdbGetObjectId() because failure will be immediately evident in the call to acdbOpenObject() when idSelected is still null:

Acad::ErrorStatus MyFunction()
ads_name anameSelected;
ads_point apointSelected;
int nResult = acedEntSel( ACRX_T(“nSelect an object: “), anameSelected, apointSelected );
if( nResult != RTNORM ) return eNotAnEntity; //or whatever
AcDbObjectId idSelected;
acdbGetObjectId( idSelected, anameSelected ); //ignoring return value!
assert( !idSelected.isNull() ); //check it nevertheless in the debug build
AcDbEntity* pEnt = NULL;
Acad::ErrorStatus es = acdbOpenObject( pEnt, idSelected, AcDb::kForRead );
if( es != Acad::eOk ) return es;
// do something with pEnt
//I confess that I don’t bother checking the
//result of AcDbObject::close() unless it matters
return Acad::eOk;

There are legitimate cases where error checking is not needed, but I think especially sample code posted on the internet should encourage good programming habits by checking the result of every function that returns one.

Leave a Reply

Your email address will not be published. Required fields are marked *