×

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

Data Types in C

Data type is a very important concept in C programming language. Simply, “A data type is the classification of data values that a data item can have.” We need to...

11 minutes read.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

Purpose of a Function Prototype in C

A function prototype in C is a declaration of a function that specifies the function's name, return type and parameters. It has the following syntax: return_type function_name(parameter_list); For example, the prototype for...

4 minutes read.

Comments in C

Comments are used to comment on the line of code in the program. Comments are a way of inserting remarks and reminders into code without affecting its behavior. The compiler...

1 minute read.

Flow chart of While loop in C

This is a flowchart that represents the process of executing the while loop in the C programming language.Generally, as we know there are three main components of while loop:1. The...

3 minutes read.

Types Of Structures In C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

3 minutes read.

Caesar Cipher Program in C

What is Caesar Cipher? The Caesar Cipher is a type of substitution cipher that is named after Julius Caesar, who is said to have used it to encrypt messages sent to...

2 minutes read.

Difference between rand() and srand() function in C

What is the rand()?The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.

Matrix Multiplication in C

Matrix Multiplication in C Matrix multiplication in C: Two matrices can be added, subtracted, multiplied, and divided. To do so, we take input from the consumer for row number, column number, first element matrix,...

3 minutes read.

Bit Fields in C

The size of a structure in C is specified in bits. The primary goal of it is to use memory efficiently, once we understand that a bit's value must fall...

3 minutes read.

Volatile in C

Introduction A volatile keyword is a qualifier in C. Qualifiers are nothing but keywords which are used to modify the properties of a variable. Qualifiers are of two types: 1) Const The const type...

3 minutes read.

Typecast vs. typedef in C

Typecast vs. typedef in C Typecast In the C programming language, converting the data type from one form to another is known as type casting or the type conversion. It is a...

5 minutes read.

Actual and Formal Parameters

Any variable declared within the parenthesis is referred to as the parameters during the function declaration. Parameters tell the function about the argument datatype, their order, and the number of...

5 minutes read.

C program to compare the two strings

C program to compare the two strings Strings can be compared either by using the string function or without using string function. First, we will look at how we can compare the strings with...

4 minutes read.

Evaluation of Arithmetic Expression in C

We can use the "eval" function in C to evaluate an arithmetic expression stored as a string. However, using "eval" is generally considered bad practice and can lead to security...

4 minutes read.

Bar3d() function in C Graphics

The bar3d function is used to create a 2-dimensional filled-in rectangular bar. We can also create three-dimensional shapes in C using helpful function. The first step in creating this 3D...

3 minutes read.

Pseudo Code in C

Pseudo code in C can be referred to as a simple way or method to write programming code or program algorithm in English. A pseudocode is an informal representation of...

4 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.

Distance Vector Routing Protocol Program in c

A distance-vector routing protocol is one of the foremost instructions of routing protocols in pc conversation principle for packet-switched networks. The hyperlink-nation protocol is the alternative foremost class.The Bellman-Ford set...

4 minutes read.

Binomial Coefficient Program in C

What is Binomial coefficient? In the given set of n possibilities, the binomial coefficient(n,k) indicates the order of choosing 'K' results from those possibilities. Binomial coeeficient of posistive n and k...

3 minutes read.