与异常一起创建一个类

时间:2016-04-22 13:33:52

标签: java class exception parameters

我为我的整个程序设置了结构但是在创建两个类TooColdException和TooHotException时遇到了麻烦,他们要有一个承包商,它接受一个String参数并将它传递给Exception类构造函数,我半创建了类但是我不知道如何完成,我的代码在下面,每个secimport java.awt。; import java.awt.event。; import javax.swing。*;

public class HotCoffeePanel extends JPanel implements ActionListener
{
  private JLabel     label;
  private JTextField temperature;
  private JButton    check_temp;

  public HotCoffeePanel()
  {
    label       = new JLabel("Water temperature  in \u00b0F:");
    temperature = new JTextField(4);
    check_temp  = new JButton("Check Temperature");

    add(label);
    add(temperature);
    add(check_temp);
    check_temp.addActionListener(this);

    setPreferredSize(new Dimension(300, 75));
    setBackground(Color.yellow);
  }

  // -----------------------------------------------------
  // Listen for the Check Temperature button and determine
  // if water is the correct temperature to brew coffee
  // -----------------------------------------------------
  public void actionPerformed(ActionEvent event)
  {
    if (Integer.parseInt(temperature.getText()) < 190)
      try
      {
        throwTooColdException();
      }
      catch(TooColdException tce)
      {
        JOptionPane.showMessageDialog(null, tce.getMessage());
      }
    else if (Integer.parseInt(temperature.getText()) > 200)
      try
      {
        throwTooHotException();
      }
      catch(TooHotException the)
      {
        JOptionPane.showMessageDialog(null, the.getMessage());
      }
    else
      JOptionPane.showMessageDialog(null, "Water temperature is fine for brewing coffee.");
  }

  //------------------------
  //  TooColdException class
  //------------------------

  public class TooColdException
  }
    public TooColdException(String  )

  }

  //------------------------
  //  TooHotException class
  //------------------------

  public class TooHotException
  }
    public TooColdException(String  )

  }



  // -------------------------------------
  // Exception thrown if water is too cold
  // -------------------------------------
  private void throwTooColdException() throws TooColdException
  {
    throw new TooColdException("Temperature is too cold to brew coffee.");
  }

  // ------------------------------------
  // Exception thrown if water is too hot
  // ------------------------------------
  private void throwTooHotException() throws TooHotException
  {
    throw new TooHotException("Temperature is too hot to brew coffee.");
  }
}  // End of HotCoffeePanel class definition

1 个答案:

答案 0 :(得分:1)

您的例外情况没有得到妥善制定。您需要正确关闭括号。此外,它们必须从Java Exception类继承。

像这样:

public class TooHotException extends Exception {
    public TooHotException(String message) {
        super(message);
    }
}