Error Handling in C
Error Handling in C
C language does not provide any direct support for error handling.
However a few methods and variables defined in errno.h header file can
be used to point out error using the return statement in a function.
In C language, a function returns -1 or NULL value in case of any error and
a global variable errno is set with the error code.
So the return value can be used to check error while programming.
What is errno?
Page 1
b. strerror() is defined in string.h library. This method returns a pointer
to the string representation of the current errno value.
An Example
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
/*
If a file, which does not exists, is opened, we will get an error
*/
fp = fopen("IWillReturnError.txt", "r");
return 0;
}
Page 2
Other ways of Error Handling
We can also use Exit Status constants in the exit() function to inform the
calling function about the error. The two constant values available for use
are EXIT_SUCCESS and EXIT_FAILURE.
These are nothing but macros defined stdlib.h header file.
It is always a good practice to exit a program with a exit status.
EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status.
In case of program coming out after a successful operation EXIT_SUCCESS
is used to show successful exit. It is defined as 0.
EXIT_FAILURE is used in case of any failure in the program. It is defined as
-1.
Division by Zero
There are some situation where nothing can be done to handle the error.
In C language one such situation is division by zero.
All you can do is avoid doing this, because if you do so, C language is not
able to understand what happened, and gives a runtime error.
Best way to avoid this is, to check the value of the divisor before using it in
the division operations.
You can use if condition, and if it is found to be zero, just display a
message and return from the function.
Page 3