Our program to this point has been prone to potential
bad numeric inputs when reading from the keyboard. The parsing methods all throw
We could now put each line that requests a number inside a small loop.
The loop could be controlled by a
boolean variable, perhaps
with a name like
isInvalid and initially set to
the reverse approach is also a possible strategy).
mainmethod or in the
As a general principle, tools shouldn't attempt to handle exceptions when the handling logic would vary depending on the code using the tool. But, it would be a tremendous burden to put each step of a program that requests a numeric input in a looped try/catch block.
Instead, we could recognize that a common approach would be to loop until the input is numeric, printing an error message each time.
We could overload the get methods in
accept an error message string, so it could do the looping for us. This way a reasonable solution would be provided, but the original method
would still be available if the programmer wants to customize the exception
If a programmer wants a different approach, they are still free to write
it in their code and use the original
KeyboardReader methods .