Error Handling
Robust error handling is crucial for creating reliable C programs. On LabEx platforms, implementing comprehensive error handling strategies ensures smooth user interactions and prevents unexpected program terminations.
Error Type |
Description |
Potential Consequences |
Buffer Overflow |
Exceeding allocated buffer size |
Memory corruption |
Invalid Input |
Non-matching input type |
Program crash |
EOF Handling |
Unexpected end of input |
Undefined behavior |
Type Conversion |
Incorrect numeric conversion |
Logical errors |
Error Handling Strategies
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
int safe_integer_input() {
char buffer[100];
char *endptr;
long value;
while (1) {
printf("Enter an integer: ");
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
printf("Input error occurred.\n");
return -1;
}
errno = 0;
value = strtol(buffer, &endptr, 10);
// Check for conversion errors
if (endptr == buffer) {
printf("No valid input detected.\n");
continue;
}
// Check for overflow
if ((value == LONG_MAX || value == LONG_MIN) && errno == ERANGE) {
printf("Number out of range.\n");
continue;
}
// Check for extra characters
if (*endptr != '\n' && *endptr != '\0') {
printf("Invalid input. Extra characters detected.\n");
continue;
}
return (int)value;
}
}
int main() {
int result = safe_integer_input();
if (result != -1) {
printf("Valid input: %d\n", result);
}
return 0;
}
Error Handling Flow
graph TD
A[User Input] --> B{Validate Input}
B --> |Valid| C[Process Input]
B --> |Invalid| D[Display Error Message]
D --> E[Request Retry]
E --> A
2. Comprehensive Error Handling Approach
#include <stdio.h>
#include <string.h>
enum InputError {
INPUT_SUCCESS,
INPUT_EMPTY,
INPUT_TOO_LONG,
INPUT_INVALID
};
enum InputError read_safe_string(char *buffer, size_t buffer_size) {
// Clear buffer
memset(buffer, 0, buffer_size);
// Read input
if (fgets(buffer, buffer_size, stdin) == NULL) {
return INPUT_EMPTY;
}
// Remove newline
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
buffer[len-1] = '\0';
len--;
}
// Check input length
if (len == 0) {
return INPUT_EMPTY;
}
if (len >= buffer_size - 1) {
return INPUT_TOO_LONG;
}
return INPUT_SUCCESS;
}
int main() {
char input[50];
enum InputError result;
while (1) {
printf("Enter a string: ");
result = read_safe_string(input, sizeof(input));
switch (result) {
case INPUT_SUCCESS:
printf("Valid input: %s\n", input);
return 0;
case INPUT_EMPTY:
printf("Error: Empty input\n");
break;
case INPUT_TOO_LONG:
printf("Error: Input too long\n");
break;
default:
printf("Unknown error\n");
}
}
}
Key Error Handling Principles
- Always validate input before processing
- Use appropriate error codes
- Provide clear error messages
- Implement retry mechanisms
- Handle edge cases
- Use safe conversion functions
By implementing these error handling techniques, developers can create more robust and reliable C programs that gracefully manage user input challenges.