Return Value Error Handling

From GPWiki
Jump to: navigation, search

When a function is called and something goes wrong, the caller often needs to know that something went wrong or it will just go on thinking everything is okay. A modern approach to this is Exceptions, but this article will discuss the classic way to do this - return values and error flags. The C standard library is a classic example of this method.

A function that may 'error' returns a certain range of values, and some values are set apart to indicate something went wrong. When the return value is a pointer (in C), the value NULL is often used. When the return value is a positive integer, the value -1 is used. Often there is a global variable that is set to an 'error code' (or error string) whenever something goes wrong.

C uses the errno-variable to provide extended Error-information. Consider for example this code:

   float x = sqrtf(-1.0f);
    if (isnan(x)) {
        printf("Error: %i\n", errno);
    } else {
        printf("%f\n", x);
    }

if sqrt receives an illegal parameter (-1) it will return NaN, a constant defined for cases where the parameter isn't legal. errno will then contain the errorcode EDOM (Math argument out of domain of function) to tell what exactly went wrong. Note that errno is only valid if the return-value of a function indicates an error.

Another contemporary library using a global error flag system is OpenGL. Unlike errno, which always returns the most recent error that was registered, OpenGL's error-flag doesn't change until glGetError was called, so it always returns the first error since the last call to glGetError.