我试图捕获NumberFormatException但是异常仍在传递

时间:2015-04-07 13:54:17

标签: java validation

我有以下示例,旨在捕捉String current = "d"不是double并且应该显示消息的事实。

当此代码运行时,由于NumberFormatException,编译器中会出现d。我相信我犯了一个非常简单的错误,但我只是看不到它。有人可以解释我哪里出错了吗?

public void runAddValidation()
{
    String current = "d";
    double vluRaised = Double.parseDouble(current);

    boolean vTypeDistanceBroke=false;

    try 
    { 
        double vFigure = vluRaised;
        vTypeDistanceBroke=false; 
    }

    catch (NumberFormatException nfe) 
    { 
        vTypeDistanceBroke=true; 
        System.out.println("Type-MoneyRaised: Failed"); 
        JOptionPane.showMessageDialog(null, "Please add a valid value (No Letters)");
    }
}

2 个答案:

答案 0 :(得分:4)

parseDouble()

中插入try-catch
public void runAddValidation()
{
    double vluRaised = 0l;
    boolean vTypeDistanceBroke;
    String current = "d";
    double vFigure = vluRaised;

    try 
    { 
        vluRaised = Double.parseDouble(current);

        vTypeDistanceBroke=false; 
    }

    catch (NumberFormatException nfe) 
    { 
        vTypeDistanceBroke=true; 
        System.out.println("Type-MoneyRaised: Failed"); 
        JOptionPane.showMessageDialog(null, "Please add a valid value (No Letters)");
    }
}

根据评论中的建议:查看parseDouble() {{1}},查看:

  

抛出:
   NullPointerException - 如果字符串为null
   NumberFormatException - 如果字符串不包含可解析的double。

答案 1 :(得分:3)

您的Try / Catch不包含异常来源。代码会在它成功之前很久就会窒息。我也冒昧地解决了代码中的一些编译错误。你应该拥有的是:

   public void runAddValidation() {
        String current = "d";
        boolean vTypeDistanceBroke=false; 

        try{ 
           //This is where you'll have a problem
          double vluRaised = Double.parseDouble(current);
          double vFigure = vluRaised;

        }

        catch (NumberFormatException nfe){ 
               vTypeDistanceBroke=true; 
               System.out.println("Type-MoneyRaised: Failed"); 
               JOptionPane.showMessageDialog(null, "Please add a valid value(No Letters)");
       } 
    }