Validation/error handling of user input values 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


#include &lt;iostream&gt;
#include &lt;stdexcept&gt;

int main() {
    int a, b;

    try {
        std::cin &gt;&gt; a;
        if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n");
        std::cin &gt;&gt; b;
        if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n");

    } catch (const std::runtime_error&amp; e) {
        std::cout &lt;&lt; e.what();
        return 1;
    }

    if (a &gt; b &amp;&amp; a &gt; 0) {
        ++a;
    } else {
        --a;
    }

    std::cout &lt;&lt; a;

    return 0;
}
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 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 &lt;stdexcept&gt;.

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.