Exceptions
Validation Errors
Validation functions can throw when an input is outside the range the program accepts.
Validation Errors
validation_errors.cpp
#include <iostream>
#include <stdexcept>
void validateScore(int score) {
if (score < 0 || score > 100) {
throw std::out_of_range("score");
}
}
int main() {
int score = ;
try {
validateScore(score);
std::cout << "score=" << score << std::endl;
std::cout << "valid=1" << std::endl;
} catch (const std::out_of_range& error) {
std::cout << "score=" << score << std::endl;
std::cout << "valid=0" << std::endl;
}
return 0;
}
#include <iostream>
#include <stdexcept>
void validateScore(int score) {
if (score < 0 || score > 100) {
throw std::out_of_range("score");
}
}
int main() {
int score = ;
try {
validateScore(score);
std::cout << "score=" << score << std::endl;
std::cout << "valid=1" << std::endl;
} catch (const std::out_of_range& error) {
std::cout << "score=" << score << std::endl;
std::cout << "valid=0" << std::endl;
}
return 0;
}
#include <iostream>
#include <stdexcept>
void validateScore(int score) {
if (score < 0 || score > 100) {
throw std::out_of_range("score");
}
}
int main() {
int score = ;
try {
validateScore(score);
std::cout << "score=" << score << std::endl;
std::cout << "valid=1" << std::endl;
} catch (const std::out_of_range& error) {
std::cout << "score=" << score << std::endl;
std::cout << "valid=0" << std::endl;
}
return 0;
}
validation
Throwing from validation keeps the normal path simple and sends invalid inputs to a handler.