LooMeenin
LooMeenin

Reputation: 818

Catching an Exception and Terminating a Program

I have an event and it throws an exception if "windowok" == false. This is how I have built the event:

public class GreenhouseControls extends Controller {

    public class WindowMalfunction extends Event {

        private Boolean windowok = false;

        private void set(Boolean windowok) {
          this.windowok = windowok ;
        }

        public WindowMalfunction(long delayTime) {
              super(delayTime);
        }

        public void action() throws ControllerException {   
          if (!windowok) {
              throw new ControllerException("Window Malfunction", 1);
          }
        } 

        public String toString() {
          return "Windok OK = " + windowok;  
        }
   }
}

The exception is caught in another class called Controller like this:

public class Controller {

    private List<Event> eventList = new ArrayList<Event>();
    private Long wait;

    public void addEvent(Event c) { 
        eventList.add(c); 
    }

    public void shutdown(Long wait) { 
        this.wait = wait;
    }

    public void run() {
       while(eventList.size() > 0)

       for(Event e : new ArrayList<Event>(eventList))
          if(e.ready()) {
              System.out.println(e);
          try {
              e.action();
          }
          catch(ControllerException ex) {
              shutdown();  // WHAT DO I DO HERE?
          }
          eventList.remove(e);
        }

}

I need to initiate the shutdown() method in the Controller class to terminate the program, but then I am required to override the shutdown() method in GreenhouseControls class to achieve this. Where should I be overriding this method in the GreenhouseControls class and should I actually be calling the shutdown() method in the catch block or just initiating a process that will call the overridden method in the GreenhouseControls class?

Upvotes: 1

Views: 139

Answers (1)

HAL9000
HAL9000

Reputation: 3751

I would simply declare an abstract method shutdown in Controller class, which will be implemented by GreenhouseControls.

I don't know the details of your architecture, however, it may be good to have an abstract class Controller (which cannot be instantiated) if more than one other classes extends it. I imagine that shutdown procedure will be different for each type of controller, then, by making it abstract, you force who extends the Controller to implement a custom shutdown procedure. If, instead, shutdown procedure is always the same you can implement it directly in Controller. Finally, if some preliminar procedures are common to all types of controller you could implement them in shutdown() inside Controller class and override the method in the derived classes by calling super.shutdown(); as first step.

Upvotes: 1

Related Questions