-4

I would like to receive two ints, one after the other, and make sure the user input is an int. If they aren't ints, I would like to allow the user to enter new input. Is an Exception a good solution here? If so, what exception should I use?

Elad
  • 13
  • 4
  • 3
    An exception is not the right choice for this issue. – Robert Andrzejuk Dec 19 '18 at 12:13
  • 1
    what you describe sound like a complete normal unexceptional case (wrong input - ask user again), exceptions are for exceptional cases (specifically cases where the code where the error occurs cannot recover from the error). Though your question is either too broad or opinion based – 463035818_is_not_an_ai Dec 19 '18 at 12:17
  • The canonical approach: https://stackoverflow.com/questions/10828937/how-to-make-cin-take-only-numbers – NathanOliver Dec 19 '18 at 13:30

2 Answers2

0

An exception is not a good solution. Exceptions are designed to handle exceptional events by allowing developers to brush their control flow below the proverbial rug while ensuring that any objects are destroyed in the process.

Based on your scenario, you're only trying to handle events that are expected. More importantly, those events are a key part of your control flow. Therefore, it makes no sense to try to hide an important part of your happy path.

Nevertheless, standard C++ does include standard exceptions designed to represent exceptions caused by logic errors (i.e., std::logic_error), which include specializations for out of bounds values (i.e., std::domain_error, std::length_error and std::out_of_range) and also invalid arguments (i.e., std::invalid_error). However, keep in mind that these exceptions are designed to be used to represent exceptional events, and not your main control flow.

RAM
  • 2,257
  • 2
  • 19
  • 41
-1

I think you can find this answer interesting: Similar question

Just check if the type is the one you desire, and then do the necessary operation i.e. re-asking the user to insert data.