Error Handling in C Programming

C programming does not provide direct support for error handling but most of the function calls return -1 or NULL in case of any error and set an error code errno. It is set as a global variable and indicates an error occurred during a function call. Various error codes are defined in <error.h> header file.

A C programmer can check the returned values and take appropriate action depending upon the return value.

perror() and strerror()

The functions perror() and strerror() can be used to display the text message associated with errno.

The perror() function displays the string you pass to it followed by the textual representation of the current errno value.

The strerror() function returns a pointer to the textual representation of the current errno value.

You should use stderr file stream to output all the errors.

Example :

#include <stdio.h>
#include <errno.h>
#include <string.h>

extern int errno ;

int main () {

   FILE * pf;
   int errnum;
   pf = fopen ("error.bin", "r");
  
   if (pf == NULL) {   
      errnum = errno;
      perror("Error message by perror");
      fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
   } else {
   
      fclose (pf);
   }
   
   return 0;
}	

Divide by Zero Error

If you try to divide any number by zero, C programming creates a runtime error. So, its always better to check the divisor value before the division.

Example :

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

main() {

  int dividend = 20, divisor = 0, quotient;

  if( divisor == 0){
    fprintf(stderr, "Division by zero ! Program execution aborted !!!\n");
    exit(-1);
  }
  else
  {
    quotient = dividend / divisor;
    printf("Value of quotient : %d\n", quotient );
    exit(0);
  }
}	

Exit Status

You can even exit a C program with the exit status as the return value. If a program executes sucessfully, the exit status will be EXIT_SUCCESS which is a macro with its value defined as 0. If there appears an error in the program, the exit status macro will be EXIT_FAILURE with the value -1.

Example :

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

main() {

  int dividend = 20, divisor = 0, quotient;

  if( divisor == 0){
    fprintf(stderr, "Division by zero ! Program execution aborted !!!\n");
    exit(EXIT_FAILURE);
  }
  else
  {
    quotient = dividend / divisor;
    printf("Value of quotient : %d\n", quotient );
    exit(EXIT_SUCCESS);
  }
}	

0 Like 0 Dislike 0 Comment Share

Leave a comment