Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C

Learn step by step



C-Error Handling

As such 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 even Unix function calls return -1 or NULL in case of any error and sets an error code errno is set which is global variable and indicates an error occurred during any function call. We can find various error codes defined in "error.h" header file.

The errno, perror() and strerror()

The C programming language provides perror() and strerror() functions which can be used to display the text message associated with errno.

  • The function perror() displays the string we pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
  • The function strerror() returns pointer to the textual representation of the current errno value.

Let us try to simulate an error condition and try to open a file which doesn't exist. Here I'm using both the functions to show the usage, but we can use one or more ways of printing our errors. Other important point to note is that we should use stderr file stream to output all the errors.


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

extern int errno ;

int main ()
{
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL)
{
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
}
else
{
fclose (pf);
}
return 0;
} RUN

Divide by zero errors

It's a common problem that at the time of dividing any number, programmers do not check if a divisor is zero and finally it creates a runtime error.

The code given below fixes this by checking if the divisor is zero before dividing:


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

main()
{
int dividend = 20;
int divisor = 0;
int quotient;

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

exit(0);
} RUN

Program Exit Status

It's common practice to exit with a value of EXIT_SUCCESS in case of programming is coming out after a successful operation. EXIT_SUCCESS is a macro and it is defined as 0.

If we have an error condition in our program and we are coming out then we should exit with a status EXIT_FAILURE which is defined as -1. So let us write above program as follows:


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

main()
{
int dividend = 20;
int divisor = 5;
int quotient;

if( divisor == 0){
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
quotient = dividend / divisor;
fprintf(stderr, "Value of quotient : %d\n", quotient );

exit(EXIT_SUCCESS);
} RUN



Related Videos