In order to program effectively, it is worth checking most function calls to verify that the function executed successfully. This can be done as follows:
if(fct(...) == error result){ /* Check error return value */ perror("fct:"); /* Output error information */ exit(error code); /* Respond to the error, e.g.*/ } /* by terminating the program */ else...
Most functions return a value of -1 or the null pointer to indicate that an error occurred when executing the function. See the chapter “Functions and variables in alphabetical order” for specific details. To the extent that a function is designed for it, the external variable errno
may also be set in such cases. The value of the errno
variable will be defined only after a call to a function where it is explicitly stated that the function sets this variable and will be preserved until it is modified by a subsequent function call. The errno
variable should be checked only if this is warranted by the value of the function result or is explicitly recommended for a particular function in the "Notes" section. None of the library functions in this manual set errno
to 0 to indicate an error.
errno
is not reset by function calls that execute successfully. In some cases, checking errno
is the only method of determining whether the function executed successfully.
Information specifying the error in more detail is prepared internally on the basis on the error code set in errno
. The corresponding error message, which contains a brief error text explaining the error, can be written to the standard output by using the perror()
function.
If more than one error occurs when processing a function call, any of the errors prescribed for the function may be returned, since the order in which the errors are detected is undefined.
All error codes to which errno
can be set and the corresponding error information are defined in the header file errno.h
. A detailed listing of these error codes can be found under the description of errno.h
.
If various types of errors and thus different error codes are possible for a function, it may be useful to query the errno
variable for the error code so as to vary the response (if appropriate) to the errors that occur. Each error code is represented by a symbolic constant defined in errno.h.
For example, ERANGE
indicates an overflow error.
A typical query could be written as shown in the following example for the signal()
function:
#include <errno.h> ... errno = 0; ... if(signal(sig, fct) == 1){ /* Check the error result */ if (errno == EFAULT) ... /* Responses to EFAULT */ else if(errno == EINVAL) ... /* Responses to EINVAL */ } else...
The conditions under which an error may occur are presented under the "Errors" heading of the individual function descriptions in the chapter “Functions and variables in alphabeticalorder”.