在Java中抛出异常

时间:2016-11-26 19:41:24

标签: java

我正在使用Java编制抵押贷款计算器。我必须使用try和catch块验证数据。我已经完成了程序的其余部分,但我无法弄清楚如何实现try和catch块。这是提示要求的内容:

"使用try和catch块编写自己的异常以验证数据。例如,贷款金额不能是负数,应该在$ 5000和$ 1,000,000之间。"

编辑:这是最终有效的try-catch块。它需要放在actionPerformed方法中,其余的数据是。我有另一个问题,代码一直为我输入的任何金额抛出异常,直到我发现我需要将for循环放在try块中。

try 
    {
      if((n1 < 5000) || (n1 > 1000000))
      throw new Exception();   

      for (int i = 0; i < term[0] * 12; i++)
      {   
        double interest_paid = n1 * (rate[0] / 12);
        double principal_paid = tr1 - interest_paid;
        n1 = n1 - principal_paid;

        //Prints the results.
        edit.append("\n  " + (i+1) + " \t\t " + (two.format(interest_paid)) 
            + " \t\t " + (two.format(principal_paid)) + " \t\t "
                + (two.format(Math.abs(n1))));            
      }
    }
    catch (Exception e)
    {        
      edit.setText("Please enter an amount between $5,000 and $1,000,000.");       
      mortText.setText("");
      out.setText("");                 
    }

1 个答案:

答案 0 :(得分:0)

这是最终有效的try-catch块。它需要放在actionPerformed方法中,其余的数据是。我有另一个问题,代码一直为我输入的任何金额抛出异常,直到我发现我需要将for循环放在try块中。

try 
{
if((n1 < 5000) || (n1 > 1000000))
  throw new Exception();   

  for (int i = 0; i < term[0] * 12; i++)
  {   
    double interest_paid = n1 * (rate[0] / 12);
    double principal_paid = tr1 - interest_paid;
    n1 = n1 - principal_paid;

    //Prints the results.
    edit.append("\n  " + (i+1) + " \t\t " + (two.format(interest_paid)) 
        + " \t\t " + (two.format(principal_paid)) + " \t\t "
            + (two.format(Math.abs(n1))));            
  }
}
catch (Exception e)
{        
  edit.setText("Please enter an amount between $5,000 and $1,000,000.");       
  mortText.setText("");
  out.setText("");                 
}