Course Content
C Tutorial
About Lesson

Handling Errors (errno, perror)

Error handling is a critical aspect of programming, especially in C, where understanding and managing errors can significantly impact the reliability and robustness of your code. Two essential components for error handling in C are errno and perror(). Let’s delve deeper into these concepts to comprehend their significance in handling errors effectively.

errno: Your Error Indicator

In C programming, errno is a global variable that signifies an error during a library function call. It’s set to a specific value by library functions to indicate the type of error encountered during execution. errno is defined in the <errno.h> header file and is typically set to zero at program startup.

When a function detects an error, it sets errno to a distinct value that corresponds to a specific error condition. For instance, if a function encounters an error while executing, it may set errno to a predefined constant to indicate the type of error that occurred.

perror(): Interpreting Errors for Developers

The perror() function is invaluable when it comes to error handling in C. It interprets the value of errno and prints a descriptive error message to the standard error stream (stderr). Developers can utilize perror() to retrieve meaningful error messages associated with the error code stored in errno.

Let’s illustrate this with a simple example:

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

int main() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
perror("Error");
fprintf(stderr, "Error opening file: %sn", strerror(errno));
} else {
// File operations go here
fclose(file);
}
return 0;
}

In this example, if fopen() fails to open the file, it sets errno to an appropriate error code. perror() then prints an error message like "Error: No such file or directory" to stderr. Additionally, strerror() complements perror() by providing a string representation of the error code.

Best Practices for Error Handling

When handling errors in C:

  1. Check Return Values: Always check the return values of library functions for errors. Most functions return specific values or set errno to indicate errors.
  2. Use errno and perror(): Leverage errno and perror() for identifying and displaying error messages, enhancing code readability and debugging.
  3. Clear Errors Before Operation: Before calling a function, reset errno to zero. This practice ensures that you’re capturing errors only from the function you’re interested in