# Asking for a number in Java Swing

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;
}

• Please show the code from where you call this method. It is difficult to answer in a good way without seeing that code. – Simon Forsberg Apr 29 '15 at 15:31
• 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 – siema Apr 29 '15 at 15:40

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?

• Thanks, If I would also like to check if number is possitive, should it be done in getNumberDialog method or no? – siema Apr 29 '15 at 21:43
• @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. – Simon Forsberg Apr 29 '15 at 22:15