Error Handling in C

C++ProgrammingServer Side Programming

Error handling is not supported by C language. There are some other ways by which error handling can be done in C language. The header file “error.h” is used to print the errors using return statement function.

It returns -1 or NULL in case of any error and errno variable is set with the error code. Whenever a function is called in C language, errno variable is associated with it. errno is a global variable and is used to find the type of error in the execution.

The following table displays some errors −

Sr.NoErrors & Error value
1I/O Error
2No such file or directory
3Argument list too long
4Out of memory
5Permission denied

There are some methods to handle errors in C language −

  • perror() − This function is used to print the error and it returns the string along with the textual representation of current errno value.

  • strerror() − This function is declared in “string.h” header file and it returns the pointer to the string of current errno value.

  • Exit status − There are two constants EXIT_SUCCESS and EXIT_FAILURE which can be used in function exit() to inform the calling function about the error.

  • Divided by zero − This is a situation in which nothing can be done to handle this error in C language. Avoid this error and you can check the divisor value by using ‘if’ condition in the program.

Here is an example of error handling in C language,


 Live Demo

#include <stdio.h>
#include <stdlib.h>

main() {
   int x = 28;
   int y = 8;
   int z;

   if( y == 0) {
      fprintf(stderr, "Division by zero!\n");
   z = x / y;
   fprintf(stderr, "Value of z : %d\n", z );


Here is the output

Value of z : 3
Published on 24-Oct-2018 10:42:29