×

Search anything:

Error Handling in C

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 30 minutes | Coding time: 5 minutes

Error handling signifies the techniques you will use to handing possible errors that the code might encounter during runtime. Handling errors are important as by doing this, we can prevent abrupt termination of a program and make it follow a deterministic path thus, giving a good user experience. Preventing all errors might not be possible as the possible situation space is large and hence, handling errors at runtime is an important strategy.

C does not support direct dealing with error handling (i.e. Exception handling) like languages such as Java and Python but still there are several ways by which we can do error handling in C.

How error handling work in C?

We have several methods and variables in error.h header file that can be used to point out the error in C by return statement in function. In C when some error occurs then -1 or NULL value is returned and a global variable errno is set with the error code.Hence we use returned values to check errors.
Whenever a function call is made in C language, a variable named errno is associated with it. It is a global variable, which can be used to identify which type of error was encountered while function execution, based on its value.

Several functions for error handling

  • perror(): returns the string passed to it along with the textual represention of the current errno value.
  • strerror() This method returns a pointer to the string representation of the current errno value.

Several error situations


Following are the errors that are defined within C and which might occur during program execution:

Erroe number value Error
1. Operation Not permitted
2. No such File or directory
3. No such process
4. Interrupted system call
5. I/O error
6. No such device or address
7. Argument list too long
8. Exec format error
9. Bad file number
10. No child processes
11. Try again
12. Out of memory
13. Permission denied

Question

Which of the following is corresponding to errno value "2"

No such file or directory
Argument list too long
Try again
Exec format error
The error corresponding to errno value 2 is "No such file or directory" and it appears when the file or directory being accessed is not existing in the respective location.

Let's see several errors in C and how to tackle them.

1. Divide by zero error in C

Most common error that we face in C is divide by zero error and many times we stuck into this while programming.
C does not have any special function or class to deal with such type of error but we can simply overcome it by checking the divisor before the division.Let us understand by following example.
Let's see when does divide by zero error comes.

#include<stdio.h> 
#include<stdlib.h>
int main() 
{ 
	int y=10/0;
	printf("result is: %.2f", y); 
	
} 

OUTPUT

6

Now we overcome this error by separate cases and display error.

#include<stdio.h> 
#include<stdlib.h>
int main() 
{ 
	int divisor = 0; 
    float y;
    if (divisor==0) 
	{ 
		printf("Division by Zero is not allowed"); 
        fprintf(stderr, "Division by zero! Exiting...\n"); 
        //fprintf is used to print something in a file here stderr 
		return -1;
	} 
	else
	{ 
		y = 10 / divisor; 
		printf("result is: %.2f", y); 
	} 
} 

divisonbyzero

Error no 2. No such file or directory

This error comes if we try to access or open a file that does not exist in the required location and following is code to display suitable error for that puropse.

#include <stdio.h>       
#include <errno.h>       
#include <string.h> 
 
int main ()
{
    FILE *fp;
    fp = fopen("a.txt", "r");
     //perform operation on fp
    //we are opening a file that does not exist
 
    return 0;
}

7

To overcome this error we check prior if file is there or not and then proceed accordingly.By using ptr!=NULL we ensure that the file does not exist and hence instead of performing operation we display suitable error message.

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

int main ()
{
    FILE *fp;
    fp = fopen("a.txt", "r");
    if(fp==NULL)
    {
	printf("Value of errno: %d\n ", errno);
    printf("The error message is : %s\n", strerror(errno));
    perror("Message from perror");	
	}
    else{
		printf("correct");
		//perform task to be done on given file
    }
   return 0;
}

err2-1

3. Use of EXIT_SUCCESS ,EXIT_FAILURE to deal with errors

This error handling is used in C as it is considered a good approach to use exit() in function and show it's status ,i.e. the it is a failure or success by EXIT_SUCCESS and EXIT_FAILURE .EXIT_SUCCESS is a macro defined by 0 and EXIT_FAILURE is defined by -1 .Following is the example of the it.

#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"); //line below exit() is not executed 
	} 

	else
	{ 
		fclose (fp); 
		exit(EXIT_SUCCESS); 
		printf("I will not be printed\n"); 
	} 
	return 0; 
} 

s3

4. Error no 9 Bad File Number Error

In general, when "Bad File Descriptor" occurs, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:

a)The fd is already closed somewhere.
b)The fd has a wrong value and is inconsistent with value from socket() api.

#include <sys/epoll.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/uio.h>
  
  int main() {
    struct epoll_event event ;
    int ret,fd, epfd ;
  
    fd = open("doc", O_RDONLY);//as this file does not exist thus error for this is got too
    if( fd < 0 )
      perror("open");
  
    event.data.fd = fd ;
    event.events = EPOLLIN|EPOLLOUT ;
  
    epfd = epoll_create(50);
    printf("%d", epfd );
  
    if( epfd < 0 )
      perror("epoll_create");
  
    ret = epoll_ctl( epfd, EPOLL_CTL_ADD, fd, &event ) ;
    if( ret < 0 )
      perror("epoll_ctl");}

open1

Hence we get this error here as we are trying to open regular files and functions like epoll(), select(), and poll() does not work on regular files.
However if it is a pipe or socket then ,then do as:
$mkfifo doc

Besides these there are several other errors in C

Syntax error :

Errors that occur when you do not follow the rules of writing C syntax is known as syntax errors. This is a compiler error which indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors.Following is the example:-

#include<stdio.h> 
#include<string.h>
int main() 
{ 
    int x = 10; 
    int y = 15;  
      
    printf("%d", (x, y)) // semicolon missed  
    getch();
    return 0;
} 

In order to remove this error , one needs to make sure that the syntax is written correctly else they will find errors like this:-

8

Logical error

On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors provide incorrect output but it seems that there is no error. They are called logical errors.
These errors depend on the logical thinking of the programmer and are easy to be found if we follow the code and determine why the program gave certain result.Hence to overcome them one needs to find out if the result comes different than what is expected.One can use different 'printf' statements to find out the exact line showing wrong working.Following is the example:-

#include<stdio.h>
#include<string.h>
int main() 
{ 
	int i = 0; 
	for(i = 0; i < 3; i++); //logical error due to ;
	{ 
		 printf("hello");
	} 
	getchar(); 
	return 0; 
} 

Given code is done as :-

Repeat five times for (i=0;i<3;i++)
... do nothing (semicolon)
Open a new scope for local variables {
... Print "hello"
Close the scope }.Hence the ouput is:-

99-1

Semantic Error

This error occurs when the statements written in the program are not adding meaning to the compiler.

#include<stdio.h>
#include<string.h>
int main() 
{ 
  int a, b, c; 
  a + b = c; //semantic error 
	getchar(); 
	return 0; 
} 

00

One has to ensure the code correctness to overcome such error.
There are other errors like Operation not permitted (like when you try to write in a file that is opened in read mode only.);Out of memory(occur when several process run at the same time)...etc.

Hence use suitable code with correct approach to avoid such errors.

Error Handling in C
Share this