Your Code Goes “Oops!”

Error messages have a notorious reputation in the computer kingdom. It’s well-deserved, but as a programmer you can better see how error messages evolved. Like documentation, i.e., the wretched manual (which is gone now), error messages are typically an afterthought in the software development cycle. It doesn’t have to be that way.

Before walking the error message path, it helps understand the difference between an error and a bug.

A bug is where your code doesn’t work, does something unexpected, or just screws up. To fix bugs, you fix your code. You address compiler or linker issues, you re-work problems, you practice defensive input and work on bullet-proofing. That’s all part of the programming process.

An error is when something else screws up, which can be anticipated. For example, a library function fails and it returns a zero, NULL, or whatever. Your code can address that issue, but for most functions you just output an error message. For example, if your code can’t allocate memory, you can send out the message, Unable to allocate memory.

You can make that message more detailed. In fact, you can list the function where the error occurred: New buffer: Failed to allocate memory. Larger programs provide error numbers, which is a source of woe for the user: 16CF: Memory allocation. That message is intended for the programmer, but yet the user will be puzzled by the 16CF part. So a better solution is possible.

File access, networking, and various operating systems functions can fail for a broad range of reasons. As an example, the rename() function returns 0 upon success. The failure value is -1, and when that value is returned, the universal variable errno is set. You can use the variable to obtain more details about why he function failed. Most programmers, however, would code the failure like this:

#include <stdio.h>

int main()
{
    int result;

    result = rename("this.txt","that.txt");
    if( result != 0 )
    {
        puts("Some kind of error!");
        return(1);
    }
    puts("File renamed");

    return(0);
}

Don’t worry if you don’t have a file named this.txt in the current directory; the program is designed to fail to show how the error message works:

Some kind of error!

Granted, that message could be more descriptive, but most programmers don’t bother with something like:

printf("Unable to rename %s\n",filename);

Even that message could be clearer: Was the file not found? Was the new name inappropriate? Could there be a file access error? It’s possible to determine the specific cause, which can help the user find a solution.

In next week’s Lesson I cover how to use the errno variable to obtain more information about file access errors.

Leave a Reply