Error Handling Techniques
Input stream errors can occur due to various reasons such as invalid input, buffer overflow, or unexpected data types.
Error Detection Mechanisms
graph TD
A[Input Stream] --> B{Error Check}
B -->|Valid Input| C[Process Data]
B -->|Invalid Input| D[Error Handling]
D --> E[User Notification]
D --> F[Input Retry]
Common Error Handling Strategies
1. Return Value Checking
int read_integer() {
int value;
while (1) {
if (scanf("%d", &value) == 1) {
return value;
} else {
printf("Invalid input. Please enter a number.\n");
// Clear input buffer
while (getchar() != '\n');
}
}
}
2. Error Handling with errno
#include <errno.h>
#include <string.h>
int process_input(char *buffer, size_t size) {
errno = 0;
if (fgets(buffer, size, stdin) == NULL) {
if (errno != 0) {
fprintf(stderr, "Input error: %s\n", strerror(errno));
return -1;
}
}
return 0;
}
Error Type |
Description |
Handling Approach |
Buffer Overflow |
Input exceeds buffer size |
Truncate or reject input |
Type Mismatch |
Incorrect input type |
Prompt for re-entry |
EOF Condition |
End of input stream |
Graceful termination |
Advanced Error Handling Technique
int robust_input(char *buffer, size_t size) {
// Clear any previous error states
clearerr(stdin);
// Attempt to read input
if (fgets(buffer, size, stdin) == NULL) {
if (feof(stdin)) {
printf("End of input reached.\n");
return -1;
}
if (ferror(stdin)) {
printf("Stream error occurred.\n");
clearerr(stdin);
return -1;
}
}
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = 0;
return 0;
}
Best Practices for Error Handling
- Always validate input
- Provide clear error messages
- Implement input retry mechanisms
- Use appropriate error checking functions
LabEx emphasizes the importance of comprehensive error handling to create robust and user-friendly C programs.