0% found this document useful (0 votes)
68 views19 pages

Error Handling

Error handling in C can be done through return values and global error variables even though C does not provide exception handling. Functions often return -1, NULL, or set the global errno variable to indicate an error occurred. errno is defined in errno.h and set to error codes like ENOENT (2) for "No such file or directory". Common error handling methods include perror() and strerror() to print the error description from errno, ferror() to check for file errors, and exit statuses to indicate success or failure.

Uploaded by

LEESHMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views19 pages

Error Handling

Error handling in C can be done through return values and global error variables even though C does not provide exception handling. Functions often return -1, NULL, or set the global errno variable to indicate an error occurred. errno is defined in errno.h and set to error codes like ENOENT (2) for "No such file or directory". Common error handling methods include perror() and strerror() to print the error description from errno, ferror() to check for file errors, and exit statuses to indicate success or failure.

Uploaded by

LEESHMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

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


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
#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("GeeksForGeeks.txt", "r");

printf("Value of errno: %d\n", errno);

return 0;
}

OutputValue 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.
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:
1.perror()
2.strerr()
3.ferror()
4.feof()
5.clearerr()
6.Exit Status
7.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.
// C implementation to see how perror() function is used to
// print the error messages.
#include <errno.h>
#include <stdio.h>
#include <string.h>

int main()
{
FILE* fp;

// If a file is opened which does not exist,


// then it will be an error and corresponding
// errno value will be set
fp = fopen(" Hello.txt ", "r");

// opening a file which does


// not exist. Output
printf("Value of errno: %d\n ", errno);
perror("Message from perror"); Value of errno: 2
Message from perror: No such file or directory
return 0;
}
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).


// C implementation to see how strerror() function is used
// to print the error messages.
#include <errno.h>
#include <stdio.h>
#include <string.h>

int main()
{
FILE* fp;

// If a file is opened which does not exist,


// then it will be an error and corresponding
// errno value will be set
fp = fopen(" GeeksForGeeks.txt ", "r");

// opening a file which does


// not exist.
printf("Value of errno: %d\n", errno);
printf("The error message is : %s\n", strerror(errno));

return 0;
}
OutputValue 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.
// C program to demonstrate the ferror() function while ((c = fgetc(file)) != EOF) {
#include <stdio.h> }

int main() if (ferror(file)) {


{ // Print an error message if an error
// Open the file in read mode occurred
FILE* file = fopen("nonexistent_file.txt", "r"); // during file reading
if (file == NULL) { printf(
// Print an error message "An error occurred while reading
// if file opening fails the file.\n");
perror("Error opening file"); }
// Return with non-zero exit status to else {
// indicate an error // Print success message if file reading
return 1; completed
} // without errors
printf("File read successfully.\n");
int c; }
// Process the character // Close the file
// Add your code here to perform operations on fclose(file);
each // Return with zero exit status to indicate successful
// character read from the file // execution
return 0;
}
Output
Error opening file: No such file or directory
3. Logical Error
Sometimes, we do not get the output we expected after the compilation and execution of a
program. Even though the code seems error free, the output generated is different from the
expected one. These types of errors are called Logical Errors. Logical errors are those errors in
which we think that our code is correct, the code compiles without any error and gives no error
while it is running, but the output we get is different from the output we expected.
In 1999, NASA lost a spacecraft due to a logical error. This happened because of some
miscalculations between the English and the American Units. The software was coded to work for
one system but was used with the other.
#include <stdio.h>

void main() {
float a = 10;
float b = 5;

if (b = 0) { // we wrote = instead of ==
printf("Division by zero is not possible");
} else {
printf("The output is: %f", a/b);
}
}

Output:

The output is: inf

INF signifies a division by zero error. In the above example, at line 8, we wanted to check whether the variable
b was equal to zero. But instead of using the equal to comparison operator (==), we use the assignment
operator (=). Because of this, the if statement became false and the value of b became 0. Finally, the else
clause got executed.
4. Semantic Error
Errors that occur because the compiler is unable to understand the written code are called Semantic Errors. A
semantic error will be generated if the code makes no sense to the compiler, even though it is syntactically
correct. It is like using the wrong word in the wrong place in the English language. For example, adding a
string to an integer will generate a semantic error.
Semantic errors are different from syntax errors, as syntax errors signify that the structure of a program is
incorrect without considering its meaning. On the other hand, semantic errors signify the incorrect
implementation of a program by considering the meaning of the program.
The most commonly occurring semantic errors are: use of un-initialized variables, type compatibility, and
array index out of bounds.
Example 1:
#include <stdio.h>

void main() {
int a, b, c;

a * b = c;
// This will generate a semantic error
}

Output:

error: lvalue required as left operand of assignment


When we have an expression on the left-hand side of an assignment operator (=), the program generates a semantic error.
Even though the code is syntactically correct, the compiler does not understand the code.

Example 2:
#include <stdio.h>

void main() { Output:


int arr[5] = {5, 10, 15, 20, 25};
5
int arraySize = sizeof(arr)/sizeof(arr[0]); 10
15
for (int i = 0; i <= arraySize; i++) 20
{ 25
printf("%d \n", arr[i]); 32764
}
}

In the above example, we printed six elements while the array arr only had five. Because we tried to access the sixth
element of the array, we got a semantic error and hence, the program generated a garbage value.
5. Linker Error
Linker is a program that takes the object files generated by the compiler and combines them into a
single executable file. Linker errors are the errors encountered when the executable file of the code
can not be generated even though the code gets compiled successfully. This error is generated when
a different object file is unable to link with the main object file. We can run into a linked error if we
have imported an incorrect header file in the code, we have a wrong function declaration, etc.

You might also like