mostafa attia mostafa attia - 1 month ago 15
Java Question

try and catch error with joptionpane

netbeans says in exception e
that variable e is not used
i don't seem to understand the problem
so please help

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DecimalFormat z = new DecimalFormat("0.00");
double x = Double.parseDouble(fnum.getText());
double y= Double.parseDouble(secondnum.getText());
try{
double f = x+y;
String number = z.format(f);
answer.setText(""+number);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "please input a valid number");
}

Answer

The warning (which can be ignored) is telling you that the variable e you've declared in your catch block is not used. I know with IntelliJ IDEA you can remove the warning by changing the name of e to ignored. I'm not sure if NetBeans has a similar feature.

However, your try block is rather pointless. It should be around your Double.parseDouble() calls, because those are what will fail if the input from the user was not something that could be interpreted as a number. The only method within your try block that could potentially throw an exception would be z.format(f) and only if z had its rounding mode set to RoundingMode.UNNECESSARY which it isn't by default.

Try something more like this.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    DecimalFormat z = new DecimalFormat("0.00");
    try  {
      double x = Double.parseDouble(fnum.getText());     
      double y = Double.parseDouble(secondnum.getText());
      double f = x + y;
      String number = z.format(f);
      answer.setText("" + number);
    } catch(NumberFormatException e) {
      JOptionPane.showMessageDialog(null, "please input a valid number");
    }
}

Edit: As pointed out in the comments on OP, catching Exception is not generally recommended, so updated to catch the more specific NumberFormatException instead.

Comments