空白文本框的例外情况

时间:2016-02-29 14:47:20

标签: exception-handling

我试图在弹出错误消息

的情况下发出异常
  

错误:金额是必需的

当他们没有在框中添加金额时。这就是我所拥有的:

String output = "Gas Amount: $" + gasAmount +
                      "\nCar Wash: " + price;
  try {
      throw new AmountException();
    JOptionPane.showMessageDialog(null, output);
  } 
  catch (AmountException ae) {
  JOptionPane.showMessageDialog(null, ae.toString(), "Error", JOptionPane.ERROR_MESSAGE);      
  }
      }

1 个答案:

答案 0 :(得分:0)

这样的事情:

public class AmountException extends Throwable
{
  public AmountException()
  {
    super("Error: Amount is required!!");
  }
}

在您的代码中:

try
{
  if (gasAmount == null)
    throw new AmountException();
  JOptionPane.showMessageDialog(null, output);
}
catch (AmountException ae)
{
  JOptionPane.showMessageDialog(null, ae.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}