Error
handling:
Error handling is the process of
detecting and responding to errors or exceptional situations that can occur
during program execution.
- Strerror():
which returns the pointer to the textual representation of the current
error value.
- Perror():
which is used to display the textual
representation.
- Exit_sucess/Exit_Failure:
is to indicate the successful or unsuccessful termination.
Example 01:
// C implementation to see how errno value is
// set in the case of any error in C
#include <stdio.h>
#include <errno.h>
int main()
{
// If a file is opened which does not exist,
// then it will be an error and corresponding
// errno value will be set
FILE * fp;
// opening a file which does
// not exist.
fp = fopen("GeeksForGeeks.txt", "r");
printf(" Value of errno: %d\n ", errno);
return 0;
}
Example 02:
// C implementation to see how perror() and strerror()
// functions are used to print the error messages.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
FILE *fp;
// If a file is opened which does not exist,
// then it will be an error and corresponding
// errno value will be set
fp = fopen(" GeeksForGeeks.txt ", "r");
// opening a file which does
// not exist.
// printf("Value of errno: %d\n ", errno);
// printf("The error message is : %s\n" ,strerror(errno));
perror("The error is : ");
return 0;
}
Example 03:
// C implementation which shows the
// use of EXIT_SUCCESS and EXIT_FAILURE.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
FILE * fp;
fp = fopen ("filedoesnotexist.txt", "rb");
if (fp == NULL)
{
printf("Value of errno: %d\n", errno);
printf("Error opening the file: %s\n",
strerror(errno));
perror("Error printed by perror");
exit(EXIT_FAILURE);
printf("I will not be printed\n");
}
else
{
fclose (fp);
exit(EXIT_SUCCESS);
printf("I will be printed\n");
}
return 0;
}
0 Comments