简体   繁体   中英

Java Programming Help- Throwing and Catching an Exception

I have a Java assignment and I need help at this point. Below is the requirement:

  1. Create a WindowMalfunction and PowerOut Events to simulate problems that may occur in a GreenhouseControls. The event should set the following boolean variables as appropriate in GreenhouseControls:

    windowok = false;
    poweron = false;

    After setting the variables, WindowMalfunction or PowerOut should throw an exception specifying the faulty condition. Create a ControllerException class that extends Exception for this purpose.

  2. If an exception is thrown from WindowMalfunction or PowerOut, the Controller catches the exception, then initiates an emergency shutdown with an appropriate message. Add a method to Controller called shutdown, and override this method in GreenhouseControls to accomplish the shutdown.

I have created the ControllerException class:

public class ControllerException extends Exception{

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

Now I have to implement it in the GreenHouseControls class. This is what I have done:

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

    public void action() throws ControllerException {
    }
}

Now, in the action() method of the WindowMalfunction I need to actually throw the ControllerException that I have created. Then, I will need to catch the exception in the Controller.run method.

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);
        }
    }
}

How do I go about doing so?

Thanks.

In the action() method you can do something like this to throw the exception you just created

throw new ControllerException();

And in run() method put the call to action() method in try-catch block something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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