Payroll-Exceptions01: Handling NumberFormatException in Payroll - Exercise

Contact Us or call 1-877-932-8228
Payroll-Exceptions01: Handling NumberFormatException in Payroll - Exercise

Payroll-Exceptions01: Handling NumberFormatException in Payroll

Duration: 5 to 10 minutes.

Our program to this point has been prone to potential bad numeric inputs when reading from the keyboard. The parsing methods all throw NumberFormatException.

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 true (using the reverse approach is also a possible strategy).

  • Inside the loop, we try the read and parse operations.
  • Then, still in the try block, change the state of the boolean to one that will end the loop (because we wouldn't get to that step unless we succeeded).
  • In the catch block, print an error message and request to try again.
  1. Where would you put this code? In the payroll main method or in the KeyboardReader class?


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 KeyboardReader to 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 handling.

If a programmer wants a different approach, they are still free to write it in their code and use the original KeyboardReader methods .