Error Handling Techniques
Introduction to Error Handling
Error handling is a crucial aspect of robust software development, especially when dealing with input validation and prime number checking.
graph TD
A[Error Types] --> B[Syntax Errors]
A --> C[Logical Errors]
A --> D[Runtime Errors]
C++ Error Handling Mechanisms
1. Exception Handling
class PrimeValidationException : public std::exception {
private:
std::string errorMessage;
public:
PrimeValidationException(const std::string& message)
: errorMessage(message) {}
const char* what() const noexcept override {
return errorMessage.c_str();
}
};
void validatePrimeInput(int number) {
try {
if (number < 2) {
throw PrimeValidationException("Input must be greater than 1");
}
if (!isPrime(number)) {
throw PrimeValidationException("Number is not prime");
}
}
catch (const PrimeValidationException& e) {
std::cerr << "Validation Error: " << e.what() << std::endl;
}
}
2. Error Handling Strategies
Strategy |
Description |
Pros |
Cons |
Exception Handling |
Throw and catch errors |
Detailed error information |
Performance overhead |
Error Codes |
Return integer error codes |
Lightweight |
Less descriptive |
Error Flags |
Set boolean error flags |
Simple implementation |
Limited error details |
Advanced Error Handling Techniques
Custom Error Logging
class ErrorLogger {
public:
static void log(const std::string& errorMessage) {
std::ofstream logFile("prime_validation_errors.log", std::ios::app);
if (logFile.is_open()) {
logFile << "[" << getCurrentTimestamp() << "] "
<< errorMessage << std::endl;
logFile.close();
}
}
private:
static std::string getCurrentTimestamp() {
auto now = std::chrono::system_clock::now();
std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
return std::ctime(¤tTime);
}
};
Comprehensive Error Handling Example
class PrimeValidator {
public:
enum class ValidationResult {
Valid,
InvalidInput,
NotPrime
};
ValidationResult validate(const std::string& input) {
try {
// Input validation
if (!isValidInteger(input)) {
ErrorLogger::log("Invalid integer input: " + input);
return ValidationResult::InvalidInput;
}
int number = std::stoi(input);
// Range validation
if (number < 2 || number > 1000000) {
ErrorLogger::log("Input out of valid range: " + std::to_string(number));
return ValidationResult::InvalidInput;
}
// Prime number check
if (!isPrimeOptimized(number)) {
ErrorLogger::log("Not a prime number: " + std::to_string(number));
return ValidationResult::NotPrime;
}
return ValidationResult::Valid;
}
catch (const std::exception& e) {
ErrorLogger::log("Unexpected error: " + std::string(e.what()));
return ValidationResult::InvalidInput;
}
}
};
Best Practices for Error Handling
- Use specific and informative error messages
- Log errors for debugging and monitoring
- Implement multiple layers of validation
- Handle unexpected scenarios gracefully
- Provide clear feedback to users
Error Handling Workflow
graph TD
A[Input Received] --> B{Validate Input}
B -->|Valid| C{Is Prime?}
B -->|Invalid| D[Log Error]
C -->|Prime| E[Process Number]
C -->|Not Prime| F[Log Non-Prime]
D --> G[Return Error]
F --> G
Conclusion
Effective error handling is essential for creating robust and reliable prime number validation systems. By implementing comprehensive error detection, logging, and management techniques, developers can create more resilient and user-friendly applications.