Error Handling Techniques
Error Handling Flow
graph TD
A[Start Program] --> B{Error Condition}
B --> |Error Detected| C[Log Error]
C --> D[Clean Up Resources]
D --> E[Exit with Error Code]
B --> |No Error| F[Continue Execution]
Error Code Strategy
Error Range |
Meaning |
0-31 |
System reserved |
32-127 |
Application-specific errors |
128-255 |
Signal-related exit codes |
Comprehensive Error Handling Example
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define FILE_ERROR 50
#define MEMORY_ERROR 51
void log_error(int error_code, const char* message) {
fprintf(stderr, "Error %d: %s\n", error_code, message);
}
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
log_error(FILE_ERROR, "Cannot open file");
exit(FILE_ERROR);
}
char *buffer = malloc(1024);
if (buffer == NULL) {
log_error(MEMORY_ERROR, "Memory allocation failed");
fclose(file);
exit(MEMORY_ERROR);
}
// File processing logic
free(buffer);
fclose(file);
return EXIT_SUCCESS;
}
Advanced Error Handling Techniques
Using errno for Detailed Errors
#include <errno.h>
#include <string.h>
#include <stdlib.h>
void handle_system_error() {
if (errno != 0) {
fprintf(stderr, "Error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
Error Handling Patterns
- Immediate Exit
- Logging and Continuing
- Graceful Degradation
- Retry Mechanism
Custom Error Handling Structure
typedef struct {
int code;
const char* message;
void (*handler)(void);
} ErrorHandler;
ErrorHandler error_map[] = {
{FILE_ERROR, "File Operation Failed", cleanup_file_resources},
{MEMORY_ERROR, "Memory Allocation Error", release_resources}
};
LabEx Development Tip
In LabEx environments, implementing robust error handling is crucial for creating reliable and maintainable C programs.
Best Practices
- Use consistent error codes
- Provide meaningful error messages
- Always clean up resources
- Log errors for debugging
- Handle different error scenarios
Error Propagation Strategies
graph LR
A[Error Detection] --> B{Error Type}
B --> |Recoverable| C[Log and Continue]
B --> |Critical| D[Exit Program]
B --> |Fatal| E[Immediate Termination]
Recommended Error Handling Approach
- Detect errors early
- Use descriptive error codes
- Implement comprehensive logging
- Ensure resource cleanup
- Provide clear error messages