Introduction To Error Handling In C Language

Error Handling definition

C programming doesn't provide any direct support for the error handling but being a system programming language, it provides you to access at lower level in the form of return values.

However a few methods and variables defined in error.h header file can be used to point out error using the return statement in a function.

Most of the C or even Unix function calls return -1 or NULL in case of any error and sets an error code.

C developers should set errno to 0 at the time of initialization of the program. A value of 0 indicates that there is no error in the program.

C provides the two functions named perror() and strerror(), can be used to display the text message associated with the errno.

    .
  • The function perror(), displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value
  • The function strerror(), which returns a pointer to the textual representation of the current errno value

errno, perror(). and strerror()

The C programming language provides perror() and strerror() functions which can be used to display the text message associated with errno.

perror(): returns the string passed to it along with the textual represention of the current errno value.

The function strerror() returns a pointer to the textual message of the current errno value. The function perror() displays a string you pass to it, followed by a colon and the textual message of the current errno value.

Example:



Output:

 Value of errno: 2
 Error printed by perror: No such file or directory
 Error opening file: No such file or directory

Division by Zero

It is a good practice to check divide by zero error. Because sometimes, user might enter a value 0 to the denominator. Here this program illustrates the concept of checking the divide by zero error.

Example:



Output:

 Enter the value of numerator and denominator: 10
 5
 Value of quotient : 2
 Enter the value of numerator and denominator: 10
 0
 Divide by zero error...!!
 Press any key to exit...