Thursday, 1 June 2017

Error Handling in C ~ GNIITHELP

Error Handling

C language does not provide direct support for error handling. However few method and variable defined in error.h header file can be used to point out error using return value of the function call. In C language, a function return -1 or NULL value in case of any error and a global variable errno is set with the error code. So the return value can be used to check error while programming.
C language uses the following functions to represent error
  • perror() return string pass to it along with the textual represention of current errno value.
  • strerror() is defined in string.h library. This method returns a pointer to the string representation of the current errno value.

Example

#include <stdio.h>       
#include <errno.h>       
#include <stdlib.h>       
#include <string.h>       
 
extern int errno;
 
main( )
{
  char *ptr = malloc( 1000000000UL);  //requesting to allocate 1gb memory space  
  if ( ptr == NULL )        //if memory not available, it will return null  
  {  
     puts("malloc failed");
     puts(strerror(errno));
     exit(EXIT_FAILURE); //exit status failure       
  }
  else
  {
     free( ptr);
     exit(EXIT_SUCCESS); //exit status Success       
  }
}
Here exit function is used to indicate exit status. Its always a good practice to exit a program with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successfull exit. It is defined as 0. EXIT_Failure is used in case of any failure in the program. It is defined as -1.

No comments:

Post a Comment