0% found this document useful (0 votes)
6 views

Error Handling Functions in C

Uploaded by

Vijay Vivian
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Error Handling Functions in C

Uploaded by

Vijay Vivian
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Error handling functions 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 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.
Example of errno

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

int main()
{
// If a file is opened which does not exist,
// then it will be an error and corresponding
// errno value will be set
FILE* fp;

// opening a file which does not exist


fp = fopen("dne.txt", "r");
printf("Value of errno: %d\n", errno);

return 0;
}
Output
Value of errno: 2
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

You might also like