Error Handling
Error handling is a crucial aspect of input validation that ensures robust and secure program execution. Proper error management helps prevent unexpected behavior and provides meaningful feedback to users.
Error Handling Strategies
1. Return Value Approach
enum ValidationResult {
VALID_INPUT = 0,
ERROR_EMPTY_INPUT = -1,
ERROR_INVALID_FORMAT = -2,
ERROR_OUT_OF_RANGE = -3
};
int validate_input(const char *input, int min, int max) {
if (input == NULL || strlen(input) == 0) {
return ERROR_EMPTY_INPUT;
}
char *endptr;
long value = strtol(input, &endptr, 10);
if (*endptr != '\0') {
return ERROR_INVALID_FORMAT;
}
if (value < min || value > max) {
return ERROR_OUT_OF_RANGE;
}
return VALID_INPUT;
}
2. Error Logging Mechanism
#include <stdio.h>
#include <time.h>
void log_validation_error(const char *input, int error_code) {
FILE *log_file = fopen("validation_errors.log", "a");
if (log_file == NULL) {
perror("Error opening log file");
return;
}
time_t current_time;
time(¤t_time);
fprintf(log_file, "[%s] Input: %s, Error Code: %d\n",
ctime(¤t_time), input, error_code);
fclose(log_file);
}
Error Handling Patterns
Pattern |
Description |
Use Case |
Return Codes |
Numeric error indicators |
Simple error communication |
Error Logging |
Persistent error tracking |
Debugging and monitoring |
Exception Handling |
Interrupt normal flow |
Complex error scenarios |
Callback Mechanism |
Custom error processing |
Flexible error management |
Error Flow Diagram
graph TD
A[Input Received] --> B{Validate Input}
B -->|Valid| C[Process Input]
B -->|Invalid| D[Error Detection]
D --> E{Error Type}
E -->|Logging| F[Write to Log]
E -->|User Feedback| G[Display Error Message]
E -->|Critical| H[Terminate Program]
Advanced Error Handling Techniques
Custom Error Handler
typedef struct {
int error_code;
const char *error_message;
void (*error_handler)(const char *input);
} ErrorHandler;
void handle_input_error(const char *input) {
ErrorHandler handlers[] = {
{ERROR_EMPTY_INPUT, "Empty input not allowed", default_error_handler},
{ERROR_INVALID_FORMAT, "Invalid input format", format_error_handler},
{ERROR_OUT_OF_RANGE, "Input out of acceptable range", range_error_handler}
};
for (size_t i = 0; i < sizeof(handlers) / sizeof(handlers[0]); i++) {
if (handlers[i].error_code == current_error) {
log_validation_error(input, handlers[i].error_code);
handlers[i].error_handler(input);
break;
}
}
}
Complete Error Handling Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INPUT_LENGTH 50
int main() {
char input[MAX_INPUT_LENGTH];
int result;
while (1) {
printf("Enter a number (1-100, or 'q' to quit): ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = 0;
if (strcmp(input, "q") == 0) {
break;
}
result = validate_input(input, 1, 100);
switch (result) {
case VALID_INPUT:
printf("Valid input: %ld\n", strtol(input, NULL, 10));
break;
case ERROR_EMPTY_INPUT:
log_validation_error(input, result);
printf("Error: Empty input\n");
break;
case ERROR_INVALID_FORMAT:
log_validation_error(input, result);
printf("Error: Invalid number format\n");
break;
case ERROR_OUT_OF_RANGE:
log_validation_error(input, result);
printf("Error: Number out of range\n");
break;
}
}
return 0;
}
Best Practices
- Always validate and handle potential errors
- Provide clear error messages
- Log errors for debugging
- Implement graceful error recovery
- Use meaningful error codes
LabEx recommends implementing comprehensive error handling to create robust and user-friendly C programs.