views:

55

answers:

3

Hi.

I have a Swing JTextBox that basically will hold a double.

I find that using:

  Double.parseDouble(this.myTB.getText());

will throw an exception (and thus program is terminated) whenever Double.parseDouble() gets invalid input.

My question: is there an easy way to NOT throw an exception, and instead return an integer (-1) saying that parseDouble() failed?

I am trying to make a popup for the user saying he or she's data field is invalid.

Thanks


EDIT:

Thanks lol. How could I forget about catching exceptions? it's been a long day!

A: 

Catch the NumberFormatException, and return your desired error value (or take some other action from within the catch clause).

double value = -1;
try {
    value =  Double.parseDouble(this.myTB.getText());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
return value;
James Van Huis
Thanks! However, it seems as though that even after we catch the exception ... it still shows in the console output. Is there anyway to supress the exception after it has been caught?
Carlo del Mundo
removing the `e.printStackTrace();` will prevent the exception from showing on the console.
James Van Huis
+1  A: 

The best way to handle this is by using a try/catch block.

try {
    return Double.parseDouble(this.myTB.getText());
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog("Oops");
    return -1;
}

The JOptionPane is a great way to display warning messages to users.

jjnguy
Thanks! However, it seems as though that even after we catch the exception ... it still shows in the console output. Is there anyway to supress the exception after it has been caught?
Carlo del Mundo
@Carlo, if you do it exactly the way I did, the exception will not get printed.
jjnguy
A: 

Use

try{
    return Double.parseDouble(this.myTB.getText());
   } catch(NumberFormatException e) {
       return -1;
   }
Frank