C Error Handling

For every c program it is required to have a proper error handling mechanism that can deal with errors which occur at runtime.Error handling is the process of responding to the occurrence of any error that occurs during the computation, of exceptions.In c programming language there is no support for error handling and garbage collection, the programmers have to make sure that a program comes out of an error condition gracefully. In C Programming Language error can be identified on the basis of return values of function calls, c function return -1 or NULL in case of any error condition and sets an error code for a global variable called errno which indicates an error occurred during any function call. You can find various error codes defined in <error.h> header file. Based on these return values programmer can take proper action to handle the error.Programmer should set errno to zero (0) at the time of initialization of the program. A value of zero(0) indicates that there is no error in the program.

errno, perror() and strerror()

In C Programming Language we have perror() and strerror() functions which can be used to display the text message associated with errno.

  • perror() – It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
  • strerror() – It returns a pointer to the textual representation of the current errno value.
  • stderr – It is file stream to output the errors.

Lets take a look at the below example code –


Preventing divide by zero errors

It is common mistake C Programmers do not take care of is not to check if a divisor is zero prior to any division operation. Lets take a look at below snippet of the code which will produce a runtime error and in most cases, exit.

Here is the example of a program in action to handle such condition –

The above program will handle a division by zero condition with the below output :


Program Exit Status

There are two macros available in C Programming Language that be used when we are exiting a program.

  • EXIT_SUCCESS – This macro is used to indicate the exiting after successful operation of program and its value is zero(0)
  • EXIT_FAILURE – This macro is used to indicate the exiting with error condition and value of this macro is -1