1

我有一个 Java 作业,此时我需要帮助。下面是要求:

  1. 创建 WindowMalfunction 和 PowerOut 事件来模拟 GreenhouseControls 中可能发生的问题。该事件应在 GreenhouseControls 中根据需要设置以下布尔变量:

    窗口确定 = 假;
    开机=假;

    设置变量后,WindowMalfunction 或 PowerOut 应抛出异常,指定故障条件。为此目的,创建一个扩展 Exception 的 ControllerException 类。

  2. 如果 WindowMalfunction 或 PowerOut 引发异常,控制器会捕获异常,然后使用适当的消息启动紧急关闭。在Controller中添加一个名为shutdown的方法,并在GreenhouseControls中重写这个方法来完成关闭。

我创建了 ControllerException 类:

public class ControllerException extends Exception{

    public ControllerException(String except){
        super(except);
    }
    public String getMessage(){
        return super.getMessage();
    }
    public void shutdown(){
    }
}

现在我必须在 GreenHouseControls 类中实现它。这就是我所做的:

public class WindowMalfunction extends Event{
    ControllerException newExcep= new ControllerException("Error:");
    public WindowMalfunction(long delayTime) { 
        super(delayTime); 
    }

    public void action() throws ControllerException {
    }
}

现在,在 WindowMalfunction 的 action() 方法中,我需要实际抛出我创建的 ControllerException。然后,我需要在 Controller.run 方法中捕获异常。

public void run() throws ControllerException {
    while(eventList.size() > 0)
    // Make a copy so you're not modifying the list
    // while you're selecting the elements in it:
    for(Event e : new ArrayList<Event>(eventList)) {
        if(e.ready()) {
            System.out.println(e);
            e.action();
            eventList.remove(e);
        }
    }
}

我该怎么做呢?

谢谢。

4

1 回答 1

0

action()方法中你可以做这样的事情来抛出你刚刚创建的异常

throw new ControllerException();

并在run()方法中将方法调用action()放在try-catch块中,例如

try{
action()
}
catch(ControllerException ex){
System.out.println("Woho caught the exception");
}
于 2013-10-08T00:31:11.003 回答