debugcppMinor
Validation/error handling of user input values
Viewed 0 times
handlingerroruservalidationinputvalues
Problem
This is a tiny learning program that lead to an interesting question: how can I best/most elegantly handle user entered numbers? This method works, fails cleanly, and reads well. It doesn't apply to types other than build in ones (as far as I know), but for floats and integers it's a nice feature. But it doesn't scale well, and seems cumbersome. Thoughts?
Read two numbers (a,b) then increment (a) by one if ( a > b ) and (a >
0) otherwise decrement (a) by one. Print (a).
Sample Input:
27
36
Sample Output:
26
Read two numbers (a,b) then increment (a) by one if ( a > b ) and (a >
0) otherwise decrement (a) by one. Print (a).
Sample Input:
27
36
Sample Output:
26
#include
#include
int main() {
int a, b;
try {
std::cin >> a;
if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n");
std::cin >> b;
if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n");
} catch (const std::runtime_error& e) {
std::cout b && a > 0) {
++a;
} else {
--a;
}
std::cout << a;
return 0;
}Solution
I question your use of exceptions to catch the invalid input. Exceptions are supposed to be used for exceptional situations. Validating user input is part of the normal functionality of the program, not an exceptional situation. It's on the lazy side to use exceptions here; you're basically treating it as a
When you do use exceptions, you should probably create a new class that's derived from one of the standard exception classes, and
I also think that when you fail, you should inform the user of that, reset the input stream, and give them another chance, rather than just exiting.
Also, sure this is just a toy, but in a real program you should separate the business logic of your program from the input and output. You might want to plug the business logic into adapters that get input from a different place and/or send the output to a different place.
goto.When you do use exceptions, you should probably create a new class that's derived from one of the standard exception classes, and
throw/catch that instead of the one from ``.I also think that when you fail, you should inform the user of that, reset the input stream, and give them another chance, rather than just exiting.
Also, sure this is just a toy, but in a real program you should separate the business logic of your program from the input and output. You might want to plug the business logic into adapters that get input from a different place and/or send the output to a different place.
Context
StackExchange Code Review Q#57423, answer score: 5
Revisions (0)
No revisions yet.