Basic Error Handling in C


Introduction

Error handling is an essential aspect of C programming, allowing you to handle unexpected situations and failures gracefully. Proper error handling can help you diagnose and resolve issues in your code. In this guide, we'll explore basic error handling techniques in C and provide sample code to illustrate their usage.


Error Codes

In C, errors are often indicated by return values or special error codes. Commonly, a function that can produce an error returns a value indicating the success or failure of the operation. A value of 0 or a positive integer typically indicates success, while a negative value indicates an error. For example, the standard library function malloc() returns NULL when it fails to allocate memory.


Error Handling Techniques

Here are some common techniques for error handling in C:

  • Check Return Values: Check the return values of functions that can produce errors. If an error occurs, take appropriate action, such as displaying an error message or freeing resources.
  • Use errno: The global variable errno is set by various library functions to indicate errors. You can check its value and use perror() to print a descriptive error message.
  • Custom Error Codes: Define your own error codes and return them from your functions to indicate specific errors in your application.

Sample Code

Let's explore some examples of basic error handling in C:


Checking Return Values

#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers = (int *)malloc(5 * sizeof(int));
if (numbers == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
return 1; // Exit with an error code
}
// Use the allocated memory
free(numbers); // Deallocate the memory
return 0;
}

Using errno

#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
fprintf(stderr, "Error opening file: %s\n", strerror(errno));
return 1;
}
// File operations
fclose(file);
return 0;
}

Custom Error Codes

#include <stdio.h>
// Custom error codes
#define ERROR_FILE_NOT_FOUND 1
#define ERROR_PERMISSION_DENIED 2
int main() {
if (fileNotFound) {
fprintf(stderr, "File not found. Error code: %d\n", ERROR_FILE_NOT_FOUND);
return ERROR_FILE_NOT_FOUND;
}
if (permissionDenied) {
fprintf(stderr, "Permission denied. Error code: %d\n", ERROR_PERMISSION_DENIED);
return ERROR_PERMISSION_DENIED;
}
return 0;
}

Conclusion

Basic error handling is a crucial skill in C programming. It allows you to detect and handle errors that can occur during the execution of your program. This guide has introduced you to fundamental error handling techniques, including checking return values, using errno, and defining custom error codes. As you continue your C programming journey, mastering error handling will help you write more robust and reliable code.