Exception Handling in C
What is Exception Handling?
Responding to unexpected occurrences in a computer program to avoid system crashes is known as exception handling. It is essential to avoid program crashes that are brought on by incorrect user input, erroneous code, device failure, lost network connections, inadequate memory, memory conflicts, or missing data. Specialized programming language structures, hardware interrupt mechanisms, or operating system inter process communication features are used for exception management. Error handling prioritizes potential problems over major ones and differs from exception handling. Error management keeps software program execution going in the usual direction.
Importance of Exception Handling in C
Exception handling is helpful when dealing with exceptions that cannot be handled locally. The exception handler moves control to where the issue may be addressed rather than displaying an error status in the program. A function has the option of handling exceptions or throwing them.
Although error management (or exception handling) is not directly supported by C, there are techniques to handle language errors. A programmer must test function return values and attempt to prevent mistakes from occurring in the first place.
Many C function calls return -1 or NULL in the event of an error, making it simple to do rapid tests on these return values using, for example, an 'if statement.' For instance, in socket programming, the returned result from functions such as socket(), listen(), and others are examined to see whether an error has occurred.
How Exception Handling Works
We must have all encountered several frequent mistakes while reading data from or writing data to a file. These mistakes typically occur:
- When we attempt to read from an empty file.
- When we make use of a newly created file.
- Whenever we attempt to write data to a file only opens in reading mode.
In this C program, we're attempting to open the file hello.txt in the reading mode so that we may read data from it. We have handled error handling using the methods described in the errno.h header file, considering the possibility that such a file doesn't exist. An error message will be generated if the requested file is missing.
Error Handling in C
1. Errno Values
In C, a variable is automatically initialized with a numeric value when a function is called, and we can use that to determine the sort of mistake that occurred while creating the code. Errno value is the name of this variable. It is a globally defined variable listed in the header file errno.h. There are 13 errno values in the C language, each with a corresponding error message.
1. Operation not permitted: When managing files in C, we occasionally try to read from or modify a file's permissions by gaining access. This error message appears if we don't have ownership rights or system privileges to view a file.
2. No such file or directory: When we attempt to access a file or directory that doesn't exist, we receive the message "No such file or directory." It also happens when the incorrect file destination path is specified.
3. No such process: The no such process problem occurs when we attempt to use specific C file handling operations that are not supported.
4. Interrupted System Call: The system calling process will not return any value and will be stopped indefinitely if we attempt to read user input but no input is available. System calls are disrupted as a result.
5. I/O error: I/O errors, also called input/output errors, are when a system cannot carry out fundamental activities like reading data from a file or transferring data from one file to another.
6. No such device or address: This error appears when we open or access a device using the wrong device path or address.
As an illustration, despite utilizing its route, a device driver has been uninstalled from the system.
7. Argument list too long: This issue frequently happens when working with several files.
For instance, if we need to count the number of files in a directory that contains a lot of files and has the string "Scaler" in the directory name, the error message "Argument list too long" will appear due to a lack of buffer space because the number of files in that directory will be equal to the argument list.
8. Exec format error: We receive this error when we attempt to run a file that is either not executable or has an incorrect executable-file format.
9. Bad file number: This error typically occurs when attempting to write to a file that has been opened with read-only permissions.
10. No child process: If a process has no more sub-processes or children, the code returns a result of -1, and an error notice showing no children is shown.
11. Try again: When there are no more process slots or insufficient memory, an attempt to establish a process fails. Then we receive a try again error.
12. Out of memory: This error happens when there is insufficient memory to carry out a process.
13. Permission denied: We get this message when we attempt to read from a file that has yet to be opened. It implies that an attempt was made to access a file in a manner that isn't allowed by its properties.
2. Error Handling Functions in C
Error checking is essential for program termination and accurate outputs. Unchecked mistakes can change the logic of the code. The C Library provides practical error management techniques, such as recursive methods for file operations. These techniques provide effective file operations and better code flow. Below are the functions for error handling in C:
1. perror():
The perror() functionis a straightforward yet effective tool for error handling. The most recent issue encountered is described in an error message printed to the standard error stream. You may get essential details about the error's root cause by using the perror() function.
Code:
#include <stdio.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
perror("Error opening file");
}
return 0;
}
2. sterror();
Based on the errno number, the strerror() method offers a mechanism to extract error messages as strings. This technique is quite helpful when handling problems programmatically and needing to extract the error message for additional processing.
Code:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
printf("Error opening file: %s\n", strerror(errno));
}
return 0;
}
3. ferror():
The ferror() function scans a file stream for errors and returns a non-zero result if one is found. It is often used following a file operation to ascertain whether any errors transpired.
Code:
#include <stdio.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
}
else {
int ch = fgetc(file);
if (ferror(file)) {
printf("Error reading file\n");
}
}
return 0;
}
4. feof():
The feof() function checks a file stream for the end-of-file indicator and returns a non-zero result if it is found. It might be helpful when reading data from a file and wondering whether you've reached the end of the file.
Code:
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file != NULL) {
int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
if (feof(file)) {
printf("\nEnd of file reached\n");
}
}
return 0;
}
5. clearerr():
The end-of-file and error signs are removed from a file stream by the clearerr() function, enabling the following file operations to proceed without being hindered. It is frequently used when an error has occurred before performing more file operations.
Code:
#include <stdio.h>
int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
}
else {
clearerr(file);
int ch = fgetc(file);
if (ferror(file)) {
printf("Error reading file\n");
}
}
return 0;
}
Correct error handling is essential when using file operations in C programming. Several error-handling techniques, including perror(), strerror(), ferror(), feof(), and clearerr(), have been covered in this course. You may successfully manage mistakes by knowing these approaches and applying them to your code, leading to more dependable and stable C programs.
Conclusion
Errno is a numerical variable used by functions in the C programming language to record errors that occur when processing files. Reading nonexistent files or using unopened files are frequent mistakes. Functional techniques such as perror(), strerror(), ferror(), feof(), clearerr(), and Exit status are employed to prevent errors. These techniques provide accurate code execution and error prevention.