C Error Handling

In this tutorial you will learn about the C Error Handling and its application with practical example.

For every c program, it is required to have a proper error handling mechanism that can deal with errors that occur at runtime. Error handling is the process of responding to the occurrence of any error that occurs during the computation, of exceptions. In the 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 errors 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. The 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 a file stream to output the errors.

Let’s take a look at the below example code –

Output:

Preventing divide by zero errors

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

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

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

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 the successful operation of the 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

Output:

In this tutorial we have learn about the C Error Handling and its application with practical example. I hope you will like this tutorial.