Error code

This is an old revision of this page, as edited by Fluzwup (talk | contribs) at 17:08, 3 November 2005 ("translated to English" some of the computerese, added example source of errno, more info on errno.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, error codes are numbered messages that correspond to faults in a specific software application, which can be caused by faulty hardware, software, or incorrect user input. Error codes are not to be confused with return codes though the latter are commonly used in error handling. Some of the most common error codes visible to users are the "Blue Screen of Death" codes provided by the Microsoft Windows operating system.

Error codes are often process global variables, such as errno in the C programming language. A return code from a function will indicate an error condition and the programmer can then check the value of errno, which is visible from anywhere in the program, against a list of possible errors to determine why the function call failed. An example of this would be a call to open a file; if the file handle returned is not valid, then errno can be examined to determine the cause of the failure. The following sample shows how the error code in errno can be used to return an error string explaining the cause of the error:

/* attempt to open file for reading */
FILE *fp = fopen("filename", "r");  
/* if file cannot be opened, print error number and error string */
if(fp == NULL)  
 printf("Cannot open file, error %i, %s\n", errno, strerror(errno));

Since the error code in this case is a global variable, it can be read or written from any portion of the program, and this can be a source of problems in a [[thread (computer science} | multithreaded]] environment, since the process global variables could be set by more than one thread, causing a race condition.

Error codes are slowly disappearing from the programmer's environment as modern object oriented computer languages replace them with exceptions. Exceptions have the advantage of being handled with explicit blocks of code, separate from the rest of the code. While it is considered poor practice, programmers often fail to check return values for error conditions, and this can cause undesirable effects as ignored error codes cause additional problems later in the program. Exceptions are implemented in such a way as to separate the error handling code from the rest of the code. Separating the error handling code makes programs easier to write, since one block of error handling code can service errors from any number of function calls. Exception handling also makes the code more readable, since it does not disrupt the flow of the code with frequent checks for error conditions.