Java编程帮助-引发和捕获异常
我有一个Java作业,现在需要帮助。要求如下:Java编程帮助-引发和捕获异常,java,Java,我有一个Java作业,现在需要帮助。要求如下: 创建窗口故障和断电事件,以模拟温室控制中可能发生的问题。事件应在Greenhouse控件中适当设置以下布尔变量: windowok=false poweron=false 设置变量后,WindowFunctional或PowerOut应引发一个异常,指定故障条件。创建一个ControllerException类,该类为此扩展Exception 如果Window故障或断电引发异常,控制器会捕获异常,然后使用适当的消息启动紧急关机。向控制器添加一个名为
poweron=false 设置变量后,WindowFunctional或PowerOut应引发一个异常,指定故障条件。创建一个ControllerException类,该类为此扩展Exception
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 {
}
}
现在,在WindowFunctional的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);
}
}
}
public void run()引发ControllerException{
while(eventList.size()>0)
//复制一份,这样您就不会修改列表
//选择其中的元素时:
对于(事件e:新阵列列表(事件列表)){
如果(如ready()){
系统输出打印ln(e);
e、 动作();
事件列表。删除(e);
}
}
}
我该怎么做呢
谢谢。在action()
方法中,您可以执行类似操作来抛出刚刚创建的异常
throw new ControllerException();
在run()
method中,在try catch
block中调用action()
method
try{
action()
}
catch(ControllerException ex){
System.out.println("Woho caught the exception");
}