C - Error Handling
C - Error Handling
C - Error Handling
As such, C programming does not provide direct support for error handling but being
a system programming language, it provides you access at lower level in the form of
return values. Most of the C or even Unix function calls return -1 or NULL in case of
any error and set an error code errno. It is set as a global variable and indicates an
error occurred during any function call. You can find various error codes defined in
<error.h> header file.
So a C programmer can check the returned values and can take appropriate action
depending on the return value. It is a good practice, to set errno to 0 at the time of
initializing a program. A value of 0 indicates that there is no error in the program.
The perror() function displays the string you pass to it, followed by a colon,
a space, and then the textual representation of the current errno value.
The strerror() function, which returns a pointer to the textual representation
of the current errno value.
Let's try to simulate an error condition and try to open a file which does not exist.
Here I'm using both the functions to show the usage, but you can use one or more
ways of printing your errors. Second important point to note is that you should use
stderr file stream to output all the errors.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main () {
FILE * pf;
int errnum;
https://www.tutorialspoint.com/cprogramming/c_error_handling.htm 1/4
6/17/24, 12:19 AM C - Error Handling
if (pf == NULL) {
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
} else {
fclose (pf);
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory
The code below fixes this by checking if the divisor is zero before dividing −
main() {
https://www.tutorialspoint.com/cprogramming/c_error_handling.htm 2/4
6/17/24, 12:19 AM C - Error Handling
exit(-1);
}
exit(0);
}
When the above code is compiled and executed, it produces the following result −
If you have an error condition in your program and you are coming out then you
should exit with a status EXIT_FAILURE which is defined as -1. So let's write above
program as follows −
main() {
if( divisor == 0) {
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
https://www.tutorialspoint.com/cprogramming/c_error_handling.htm 3/4
6/17/24, 12:19 AM C - Error Handling
exit(EXIT_SUCCESS);
}
When the above code is compiled and executed, it produces the following result −
Value of quotient : 4
https://www.tutorialspoint.com/cprogramming/c_error_handling.htm 4/4