Error Handling in C


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
5
2No such file or directory
2
3Argument list too long
7
4Out of memory
12
5Permission denied
13

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,

Example

 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");
      exit(EXIT_FAILURE);
   }
   z = x / y;
   fprintf(stderr, "Value of z : %d\n", z );
   exit(EXIT_SUCCESS);
}

Output

Here is the output

Value of z : 3

Updated on: 25-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements