×

Error handling in C

Error handling in C: The C programming standard does not provide direct convenience for handling the errors. However, being a system programming language, it definitely will give access to handling the error in a lower level of the form of some return values. Many function calls either return -1 or NULL in case of any error.

This has been used to set the global variable, indicating an error that might occur during a function call. Error codes are defined within <error.h> header file. Hence, a developer can check the return value can act accordingly. It is advised to set errno to 0 at the time of initializing any program. If the value of errno returns a 0, then it can be concluded that there are no errors in that particular program or application.

Even though C generally never supports the handling of errors and exception, there are various ways to achieve First and foremost, a developer should avoid making errors, but we humans tend to make mistakes most of the time knowingly or unknowingly. Nevertheless, one can prevent errors by running test case values from the function.

Methods of handling errors in C:

  1. Global variable Errno

In the C standard, this variable is referred to as an ‘errno’ and is assigned with a specific number of codes that can be used within the program to detect the type of the error. Such a type of error is always declared in the file termed as an error.h, hence there are various errors such as;

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

E.g.:

 #include <stdio.h>
 #include <errno.h>
 int main()
 {
 FILE *a;
 a = fopen(“Tutorials.txt” , “r”);
 printf (“The value of the error number as errno is: %d \n”, errno);
 return 0;
 } 

Output

Error handling in C

Since, we are trying to open and read a file that does not exist, it will hence give the error that is being assigned to a value, that is, errno 2.

prror() and strerror()

These are the two methods that are used to display the errno just the same way in the above program.

perror()

This function takes the message that has to be displayed which also shows the textual representation of the errno.

Syntax

void perror (const char *s)

Where,s is a string or message to be printed before the error message.

strerror()

This is the function that points to a string or a message of the errno value of this function. It is defined using <string.h> header library.

Syntax

char *strerror(int errno)

E.g.:

 #include <stdio.h>
 #include <errno.h>
 #include <string.h>
 extern int errno ;
 int main ()
 {
 FILE * f;
 int errornum;
 f = fopen ("article.txt", "rb");
 if (f == NULL)
 {
 errornum = errno;
 fprintf(stderr, "The Value of errno: %d\n", errno);
 perror("Error message that is printed by perror");
 fprintf(stderr, "Error message for opening file that does not exist: %s\n", strerror( errornum ));
 }
 else
 {
 fclose (f);
 }
 return 0;
 } 

Output

Error handling in C

Opening a file that is not present in the system so as to print the message using perror() and strerror() which again will print the message in accordance with the errno.

exit() status

The exit constant in this particular function is used to inform the calling function about the error. The constant values that will be ready for use are EXIT_SUCCESS and EXIT_FAILURE. There are macro defined libraries and are present within the <stdlib.g> header file.

E.g.:

 #include <stdio.h>
 #include <errno.h>
 #include <stdlib.h>
 #include <string.h>
 extern int errno;
 void main()
 {
 char *ptr = malloc(100UL);/requesting to allocate memory space
 if (ptr == NULL)    //if memory not available, it will return null
 { 
 puts("malloc failed");
 puts(strerror(errno));
 exit(EXIT_FAILURE);     //exit status failure
 }
 else
 {
 free( ptr);
 exit(EXIT_SUCCESS);     //exit status Success     
 }
 } 

Divide by zero error

As the name itself defines, this error is displayed or will occur every time a compiler encounters a divisor zero before a division command. Hence, it leads to dividing by zero error.

E.g.:

 #include<stdio.h>
 #include <stdlib.h>
 void function(int);
 int main()
 {
 int x = 0;
 function(x);
 return 0;
 }
 void function(int x)
 {
 float f;
 if (x==0)
 {
 printf("Division by Zero is not allowed as it leads to the error");
 fprintf(stderr, "Division by zero error\n");
 exit(EXIT_FAILURE);
 }
 else
 {
 f = 10 / x;
 printf("f(x) is: %.5f", f);
 }
 } 

Output

Error handling in C

Related Topics

Nested Loops in C Programming Examples

A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a “loop inside the...

6 minutes read.

getc() function in C

Getc is one of the file handling technique in C. The Getc() is a C library function gets the next character or new characters  from the specific stream and supports...

4 minutes read.

Floor() Function in C

Floor() function is a built-in function in C which is defined in the math.h header file. This function is used to return the nearest integer value which is less than...

4 minutes read.

Multiplication Table in C

Displaying table up to 10 #include <stdio.h> int main() {     int num, i = 1;     printf("     Enter any Number:");     scanf("%d", &num);     printf("Multiplication table of %d: ", num);  ...

1 minute read.

Types of Array in C

What is an Array? One value can be stored in a variable at once. How many variables will you need if you have 100 values? Well, the answer isn't 100. It...

14 minutes read.

Factorial Program in C using For Loop

Before move on the factorial program. We have to know about the for loop in C programming language. The syntax of the For Loop is: for (initialization statement; test expression; an increment...

3 minutes read.

Storage Class in C

C storage class is used to define the scope variables and function. There are four various types of storage classes that are given below. auto: The auto keyword is the default...

1 minute read.

#undef in C

#undef in C In the C programming language, the #undef directive is used to undefine the macro or any constant, which will be defined by the preprocessor directive #define. The #undef...

3 minutes read.

Find occurrence of substring in C using function

Introduction: In this article, we discuss finding the occurrence of a substring in C using function. This software takes strings and substrings as input and counts the occurrences of substrings within...

3 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

How to convert a number to words in C

There are many ways available for converting an integer or a number to its word form. For example, consider a number as 12345. This number can be represented in two...

3 minutes read.

fgets() function in C

fgets() function is present in standard input and output library i.e, stdio.h library. It is a built-in function or pre-define function. It is used to read the specified stream from...

4 minutes read.

Static function in C

The functions in the C programming language are by default global. This means the programmer can easily access the function which is outside from the file where it was initially...

3 minutes read.

Execution flow of C program

There are various steps of the execution of the C program that is given below. The following step of the execution Write source codes Preprocess Compile Link edit Load Execute Editor or...

1 minute read.

C vs Java Strings

String in C In C, we can define a string as a bunch of characters. A character array is distinguished from a string by the presence of the special character '\0'...

5 minutes read.

Segmentation Fault in C

Segmentation Fault in C In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating...

4 minutes read.

Control statement in C

What is a control statement? A control statement helps us to control the flow of the program. The control statement helps us to execute the program's instructions in a user-defined order....

8 minutes read.

Random function in C

Random function in C In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not...

4 minutes read.

Int in C

The keyword int in C programming stands for integer and it is a data type which is used for variable declarations or declaration of functions of different types. Similar to...

4 minutes read.

memcpy() in C

Introduction: Here we discuss about the memcpy() function in C. The memcpy() function is also called the Copy Memory Block function. Used to create a copy of a specific drawing...

4 minutes read.