0
\$\begingroup\$

Is it good way of asking for a number? Should that function return 0 if there is an error?

private int getNumberDialog(String message) {
            try {
                String resultInString = JOptionPane.showInputDialog(message);
                int result = Integer.parseInt(resultInString);
                return result;
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "You didn't gave a number");
            }
            return 0;
        }
\$\endgroup\$
  • \$\begingroup\$ Please show the code from where you call this method. It is difficult to answer in a good way without seeing that code. \$\endgroup\$ – Simon Forsberg Apr 29 '15 at 15:31
  • \$\begingroup\$ I just use it by: public void playForMeNrTimes() { int howManyTimes = getNumberDialog("How many times?"); game.playForMeNrTimes(howManyTimes); } I just want to know if handling an exception this way is ok \$\endgroup\$ – siema Apr 29 '15 at 15:40
2
\$\begingroup\$

Avoid using "special return values" in code for when errors occur. It should be up to the calling code how to handle the situation.

I would let the getNumberDialog utility function re-throw the exception:

private int getNumberDialog(String message) throws NumberFormatException {
    String resultInString = JOptionPane.showInputDialog(message);
    int result = Integer.parseInt(resultInString);
    return result;
}

And in your usage code, you catch the exception:

try {
    int times = getNumberDialog("How many times?");
    game.playForMeNrTimes(times);
} catch (NumberFormatException ex) {
    JOptionPane.showMessageDialog(null, "You didn't gave a number");
}

The key here is that the utility-function getNumberDialog doesn't know about any context. It doesn't know how the returned value will be used, so how can it possibly decide on a default value to use in the case of an error?

\$\endgroup\$
  • \$\begingroup\$ Thanks, If I would also like to check if number is possitive, should it be done in getNumberDialog method or no? \$\endgroup\$ – siema Apr 29 '15 at 21:43
  • \$\begingroup\$ @siema Ask yourself the question: Do you always want to make sure the number is positive? You probably don't want to do it inside that method. \$\endgroup\$ – Simon Forsberg Apr 29 '15 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.