C Error Handling

C Error Handling


1

2

3

Value of errno: 2

Error: No such file or directory

fopen failed due to: No such file or directory

 

Preventing divide by zero errors

It is common mistake C Programmers do not take care of is not to check if a divisor is zero prior to any division operation. Lets take a look at below snippet of the code which will produce a runtime error and in most cases, exit.

1

2

3

4

int dividend = 20;

int divisor = 0;

int quotient;

quotient = (dividend/divisor); /* This will produce a runtime error! */

Here is the example of a program in action to handle such condition –

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#include <stdio.h>

#include <stdlib.h>

 

main()

{

   int dividend = 20;

   int divisor = 0;

   int quotient;

 

   if( divisor == 0){

      fprintf(stderr, "Division by zero case! Exiting...\n");

      exit(-1);

   }

   quotient = dividend / divisor;

   fprintf(stderr, "Value of quotient : %d\n", quotient );

 

   exit(0);

}

The above program will handle a division by zero condition with the below output :

Output: