Robust Error Handling
Error Handling Strategies
Comprehensive Error Management Framework
graph TD
A[Error Detection] --> B{Error Type}
B --> |Recoverable| C[Graceful Recovery]
B --> |Critical| D[Controlled Shutdown]
C --> E[Retry Mechanism]
D --> F[Clean Resource Release]
1. Error Logging Techniques
Structured Error Logging
enum LogLevel {
LOG_DEBUG,
LOG_INFO,
LOG_WARNING,
LOG_ERROR,
LOG_CRITICAL
};
void log_error(enum LogLevel level, const char *message) {
FILE *log_file = fopen("system_log.txt", "a");
if (log_file) {
fprintf(log_file, "[%s] %s\n",
level == LOG_ERROR ? "ERROR" : "CRITICAL",
message);
fclose(log_file);
}
}
2. Resource Management
RAII-like Resource Handling
typedef struct {
int fd;
char *buffer;
} ResourceContext;
ResourceContext* create_resource_context(int size) {
ResourceContext *ctx = malloc(sizeof(ResourceContext));
if (!ctx) {
return NULL;
}
ctx->buffer = malloc(size);
ctx->fd = open("example.txt", O_RDWR);
if (ctx->fd == -1 || !ctx->buffer) {
// Cleanup on failure
if (ctx->fd != -1) close(ctx->fd);
free(ctx->buffer);
free(ctx);
return NULL;
}
return ctx;
}
void destroy_resource_context(ResourceContext *ctx) {
if (ctx) {
if (ctx->fd != -1) close(ctx->fd);
free(ctx->buffer);
free(ctx);
}
}
3. Error Handling Patterns
Retry Mechanism
#define MAX_RETRIES 3
int robust_network_operation() {
int retries = 0;
while (retries < MAX_RETRIES) {
int result = network_call();
if (result == 0) {
return SUCCESS;
}
if (is_transient_error(result)) {
sleep(1 << retries); // Exponential backoff
retries++;
} else {
return FATAL_ERROR;
}
}
return RETRY_EXHAUSTED;
}
4. Error Handling Best Practices
Practice |
Description |
Fail Fast |
Detect and handle errors immediately |
Minimal Error State |
Keep error handling code concise |
Comprehensive Logging |
Record detailed error information |
Graceful Degradation |
Provide alternative paths on failure |
5. Advanced Error Handling
Custom Error Handling Macro
#define SAFE_CALL(call, error_handler) \
do { \
if ((call) == -1) { \
perror("Operation failed"); \
error_handler; \
} \
} while(0)
// Usage example
SAFE_CALL(
open("config.txt", O_RDONLY),
{
log_error(LOG_ERROR, "Failed to open config");
exit(EXIT_FAILURE);
}
)
6. Error Recovery Strategies
Multilevel Error Handling
int process_data() {
int result = PRIMARY_OPERATION();
if (result != SUCCESS) {
// Try alternative method
result = SECONDARY_OPERATION();
if (result != SUCCESS) {
// Final fallback
result = FALLBACK_OPERATION();
}
}
return result;
}
Learning with LabEx
At LabEx, we provide advanced system programming courses that teach robust error handling techniques through practical, hands-on exercises, helping developers build resilient software solutions.