繁体   English   中英

Java编程帮助-引发和捕获异常

[英]Java Programming Help- Throwing and Catching an Exception

我有一个Java作业,目前需要帮助。 以下是要求:

  1. 创建一个WindowMalfunction和PowerOut事件以模拟GreenhouseControls中可能出现的问题。 该事件应在GreenhouseControls中适当设置以下布尔变量:

    windowok = false;
    poweron =假;

    设置变量后,WindowMalfunction或PowerOut应该引发异常,以指定错误条件。 为此创建一个ControllerException类,该类扩展了Exception。

  2. 如果从WindowMalfunction或PowerOut引发异常,则Controller会捕获该异常,然后使用适当的消息启动紧急关机。 向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);
        }
    }
}

我该怎么做?

谢谢。

action()方法中,您可以执行以下操作以抛出刚创建的异常

throw new ControllerException();

然后在run()方法中,将对action()方法的调用放在try-catch块中,例如

try{
action()
}
catch(ControllerException ex){
System.out.println("Woho caught the exception");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM