C Error Handling

C  Error Handling:

C programming doesn’t provide direct support for error handling but being a system programming language, it provides us access at lower level in the form of return values. Most of the C or even Unix function calls return null or -1 in case of any error and set an error code errno. It is set as a global variable and indicates an error occurred during any function call. we find various error codes defined in <error.h> header file.
So a C programmer able to check the returned values and can take appropriate action depending on the return value. It is a good practice, to set errno to 0 at the time of initialization of program. A value of 0 indicates that there is no error in the program.
errno, perror(). and strerror() in C:-
The C programming language provides perror() and strerror()functions which can be used to show the text message associated with errno.
• The perror() function displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
• The strerror() function, which returns a pointer to the textual representation of the current errno value.

Example 1: Divide by Zero Errors

#include<stdio.h>

#include<stdlib>

main()

{

int dividend1 = 20;

int divisor1 = 0;

int quotient1;

if( divisor1 == 0)

{

fprintf(stderr, “Division by zero! Exiting…\n”);

exit(-1);

}

quotient1 = dividend1 / divisor1;

fprintf(stderr, “Value of quotient : %d\n”, quotient1 );

exit(0);

return 0;

}

Output

Division by zero! Exiting…

Example 2:Program Exit Status

#include<stdio.h>

#include<stdlib>

main()

{

int dividend1 = 20;

int divisor1 = 5;

int quotient1;

if( divisor1 == 0)

{

fprintf(stderr, “Division by zero! Exiting…\n”);

exit(EXIT_FAILURE);

}

quotient1 = dividend1 / divisor1;

fprintf(stderr, “Value of quotient : %d\n”, quotient1 );

exit(EXIT_SUCCESS); return 0;

}

Output

Value of quotient : 4

Leave a Reply

Your email address will not be published. Required fields are marked *