Error handling in C is an essential concept to ensure robust and reliable programs.
Unlike some modern programming languages, C does not provide built-in support
for error handling, such as exceptions. Instead, error handling in C is implemented
using traditional mechanisms like return values, error codes, and global variables.
1. Using Return Values for Error Handling
Functions in C often return a specific value to indicate success or failure. This
value can be checked to handle errors appropriately.
Example: Checking Return Values
#include <stdio.h>
int divide(int a, int b, int* result) {
if (b == 0) {
return -1; // Return an error code for division by zero
}
*result = a / b;
return 0; // Success
}
int main() {
int a = 10, b = 0, result;
if (divide(a, b, &result) != 0) {
printf("Error: Division by zero\n");
} else {
printf("Result: %d\n", result);
}
return 0;
}
, In this example, the divide function returns -1 to indicate an error (division by
zero), and the caller checks the return value.
2. Global Variable errno
The <errno.h> header file provides a global variable errno that stores error codes
set by certain library functions. These codes indicate the type of error
encountered.
Common Error Codes
EIO: Input/output error
ENOMEM: Out of memory
EINVAL: Invalid argument
EBADF: Bad file descriptor
Example: Using errno
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE* file = fopen("nonexistent.txt", "r");
if (file == NULL) {
printf("Error: %s\n", strerror(errno)); // strerror() provides a readable error
message
}
return 0;
}
In this example, attempting to open a nonexistent file sets errno. The strerror()
function converts the error code to a human-readable message.
3. Custom Error Codes