Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer has to prevent errors in the first place and test return values from the functions.
A lot of C function calls return -1 or NULL or set an in case of an error code as the global variable errno, so quick tests on these values are easily done with an instance of ‘if statement’.
What is errno?
errno is a global variable indicating the error occurred during any function call and it is defined inside <errno.h> header file.
When a function is called in C, a variable named errno is automatically assigned a code (value) which can be used to identify the type of error that has been encountered. Different codes (values) for errno mean different types of errors.
Below is a list of a few different errno values and their corresponding meaning:
| errno 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
|
The argument list is too long |
|
8
|
Exec format error |
|
9
|
Bad file number |
|
10
|
No child processes |
|
11
|
Try again |
|
12
|
Out of memory |
|
13
|
Permission denied |
Example of errno
C
#include <errno.h>
#include <stdio.h>
int main()
{
FILE* fp;
fp = fopen("GeeksForGeeks.txt", "r");
printf("Value of errno: %d\n", errno);
return 0;
}
|
Note: Here the errno is set to 2 which means “No such file or directory”. It may give Errno 13 in online IDE, which says permission denied.
Different Methods for Error Handling in C
Different methods are used to handle different kinds of errors in C. Some of the commonly used methods are:
- perror()
- strerr()
- ferror()
- feof()
- clearerr()
- Exit Status
- Divide by Zero Error
1. perror()
The perror() function is used to show the error description. It displays the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.
Syntax
void perror(const char *str);
Parameters
- str: It is a string containing a custom message to be printed before the error message itself.
Example
C
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main()
{
FILE* fp;
fp = fopen(" GeeksForGeeks.txt ", "r");
printf("Value of errno: %d\n ", errno);
perror("Message from perror");
return 0;
}
|
Output
Value of errno: 2
Message from perror: No such file or directory
2. strerror()
The strerror() function is also used to show the error description. This function returns a pointer to the textual representation of the current errno value.
Syntax
char *strerror(int errnum);
Parameters
- errnum: It is the error number (errno).
Example
C
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main()
{
FILE* fp;
fp = fopen(" GeeksForGeeks.txt ", "r");
printf("Value of errno: %d\n", errno);
printf("The error message is : %s\n", strerror(errno));
return 0;
}
|
Output
Value of errno: 2
The error message is : No such file or directory
3. ferror()
The ferror() function is used to check whether an error occurred during a file operation.
Syntax
int ferror(FILE *stream);
Parameters
- stream: It is the pointer that points to the FILE for which we want to check the error.
Return Value
- It returns a non-zero value if an error occurred, otherwise it returns 0.
Example
C
#include <stdio.h>
int main()
{
FILE* file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
int c;
while ((c = fgetc(file)) != EOF) {
}
if (ferror(file)) {
printf(
"An error occurred while reading the file.\n");
}
else {
printf("File read successfully.\n");
}
fclose(file);
return 0;
}
|
Output
Error opening file: No such file or directory
4. feof()
The feof() function is used to check whether end-of-file indicator is set for a file steam.
Syntax
int feof(FILE *stream);
Parameters
- stream: It is the pointer that points to the FILE for which we want to check the error.
Return Value
- It returns a non-zero value if an error occurred, otherwise, it returns 0.
Example
C
#include <stdio.h>
int main()
{
FILE* fptr = fopen("filename.txt", "r");
if (fptr == NULL) {
perror("Error opening the file");
return 1;
}
if (ferror(fptr)) {
perror("Error occurred during file operations");
}
fclose(fptr);
return 0;
}
|
Output
Error opening the file: No such file or directory
5. clearerr()
The clearerr() function is used to clear both end-of-file and error indicators for a file stream.
Syntax
void clearerr(FILE *stream);
Parameters
- stream: It is the pointer that points to the FILE for which we want to check the error.
Example
C
#include <stdio.h>
int main()
{
FILE* file = fopen("file.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
if (ferror(file)) {
printf("An error occurred while performing file "
"operations.\n");
}
clearerr(file);
fclose(file);
return 0;
}
|
6. Exit Status
Exit status is the value returned by the program after its execution is completed which tells the status of the execution of the program.
The C standard specifies two constants: EXIT_SUCCESS and EXIT_FAILURE, that may be passed to exit() to indicate successful or unsuccessful termination, respectively. These are macros defined in <stdlib.h> header file.
Example
C
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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");
}
else {
fclose(fp);
exit(EXIT_SUCCESS);
printf("I will not be printed\n");
}
return 0;
}
|
Output
Value of errno: 2
Error opening the file: No such file or directory
Error printed by perror: No such file or directory
7. Divide by Zero Errors
A common pitfall made by C programmers is not checking if a divisor is zero before a division command. Division by zero leads to undefined behavior, there is no C language construct that can do anything about it. Your best bet is to not divide by zero in the first place, by checking the denominator.
Example
C
#include <stdio.h>
#include <stdlib.h>
void function(int);
int main()
{
int x = 0;
function(x);
return 0;
}
void function(int x)
{
float fx;
if (x == 0) {
printf("Division by Zero is not allowed");
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
else {
fx = 10 / x;
printf("f(x) is: %.5f", fx);
}
}
|
Output
Division by zero! Exiting...
Similar Reads
Error Handling in C
Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer has to prevent errors in the first place and test return values from the functions. A lot of C function calls return -1 or NULL or set an i
8 min read
Header Files in C
In C language, header files contain a set of predefined standard library functions. The .h is the extension of the header files in C and we request to use a header file in our program by including it with the C preprocessing directive "#include". C Header files offer the features like library functi
7 min read
Header Files in C
In C language, header files contain a set of predefined standard library functions. The .h is the extension of the header files in C and we request to use a header file in our program by including it with the C preprocessing directive "#include". C Header files offer the features like library functi
7 min read
Storage for Strings in C
In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays [GFGTABS] C char str[4] = "GfG"; /*One extra for string terminator*/ /* OR */ char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */ [/GFGTA
5 min read
Storage for Strings in C
In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays [GFGTABS] C char str[4] = "GfG"; /*One extra for string terminator*/ /* OR */ char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */ [/GFGTA
5 min read
Char Comparison in C
Char is a keyword used for representing characters in C. Character size in C is 1 byte. There are two methods to compare characters in C and these are: Using ASCII valuesUsing strcmp( ) .1. Using ASCII values to compare characters The first method is pretty simple, we all know that each character ca
3 min read
C Programming Interview Questions (2025)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the oldest and most popular programming languages. There are many applications in which C programming language is us
15+ min read
C Programming Interview Questions (2025)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the oldest and most popular programming languages. There are many applications in which C programming language is us
15+ min read
C Programming Language Tutorial
C is a general-purpose, procedural, and middle-level programming language used for developing computer software, system programming, applications, games, and more. Known for its simplicity and efficiency, C is an excellent choice for beginners as it provides a strong foundation in programming concep
6 min read
C Programming Language Tutorial
C is a general-purpose, procedural, and middle-level programming language used for developing computer software, system programming, applications, games, and more. Known for its simplicity and efficiency, C is an excellent choice for beginners as it provides a strong foundation in programming concep
6 min read
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the con
6 min read
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the con
6 min read
Splint -- A C program verifier
C compiler is pretty vague in many aspects of checking program correctness, particularly in type checking. Careful use of prototyping of functions can assist modern C compilers in this task. However, there is still no guarantee that once you have successfully compiled your program that it will run c
1 min read
C Programming Language Standard
Introduction:The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the featur
6 min read
C Programming Language Standard
Introduction:The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the featur
6 min read
grapherrormsg() function in C
The header file graphics.h contains grapherrormsg() function which returns an error message string. Syntax : char *grapherrormsg( int errorcode ); where, errorcode: code for the respective error Illustration of the grapherrormsg() : In the below program, gd = DETECT is not written and thus program m
1 min read
Bank account system in C using File handling
This article focuses on how to create a bank account system using C language and File handling in C. Approach:Let's discuss the approach in detail, covering all the functions and their explanation in detail- Create a Menu in the main function and create different functions for the Menu, which will b
12 min read
Command Line Arguments in C
The most important function of C is the main() function. It is mostly defined with a return type of int and without parameters. int main() { ... }We can also give command-line arguments in C. Command-line arguments are the values given after the name of the program in the command-line shell of Opera
4 min read
Command Line Arguments in C
The most important function of C is the main() function. It is mostly defined with a return type of int and without parameters. int main() { ... }We can also give command-line arguments in C. Command-line arguments are the values given after the name of the program in the command-line shell of Opera
4 min read