引发并捕获异常

时间:2020-06-07 21:25:17

标签: java

我有一个Java作业,但在以下几点上有些卡住:

  1. 创建一个WindowMalfunction和PowerOut事件以模拟可能在GreenhouseControls中发生的问题。该事件应在GreenhouseControls中适当设置以下布尔变量: windowok = false; poweron =假; 设置变量后,WindowMalfunction或PowerOut应该引发异常,以指定错误条件。为此创建一个ControllerException类,该类扩展了Exception。
  2. 如果WindowMalfunction或PowerOut抛出异常,则Controller会捕获该异常,然后使用适当的消息启动紧急关机。向Controller添加一个名为shutdown的方法,并在GreenhouseControls中重写此方法以完成关闭。
  3. 在GreenhouseControls中添加一个名为errorcode的实例变量。它使用int变量错误代码(对于WindowMalfunction为1,对于PowerOut为2)中的错误代码指示问题的性质,在当前目录中名为error.log的文本文件中记录时间和关闭原因,并进行打印到控制台。然后,它会在退出之前进行序列化并将整个GreenhouseControls对象保存在当前目录的dump.out文件中。

这是我到目前为止所做的(不多),我不确定如何抛出和捕获异常。

    private boolean windowork;

    public class WinidowMalfunction extends Event {
        public WinidowMalfunction(long delayTime) {
            super(delayTime);
        }

        public void action() {
            windowork = false;
        }
    }

    private boolean poweron;

    public class PowerOut extends Event {
        public PowerOut(long delayTime) {
            super(delayTime);
        }

        public void action() {
            poweron = false;
        }
    }

    public class ControllerException extends Exception {
        public ControllerEception(String except) {
            super(except);
        }

        public String getMessage() {
            return super.getMessage();
        }

        public void shutdown() {

        }
    }

如果需要的话,这里是完整的项目代码: GreenhouseControls.java

import java.io.*;
import java.util.Calendar;
import java.util.Scanner;

import tme3.*;

public class GreenhouseControls extends Controller {
    private boolean light = false;
    private boolean water = false;
    private String thermostat = "Day";
    private String eventsFile = "example1.txt";


    public class LightOn extends Event {
        public LightOn(long delayTime) { super(delayTime); }
        public void action() {
            // Put hardware control code here to
            // physically turn on the light.
            light = true;
        }
        public String toString() { return "Light is on"; }
    }
    public class LightOff extends Event {
        public LightOff(long delayTime) { super(delayTime); }
        public void action() {
            // Put hardware control code here to
            // physically turn off the light.
            light = false;
        }
        public String toString() { return "Light is off"; }
    }
    public class WaterOn extends Event {
        public WaterOn(long delayTime) { super(delayTime); }
        public void action() {
            // Put hardware control code here.
            water = true;
        }
        public String toString() {
            return "Greenhouse water is on";
        }
    }
    public class WaterOff extends Event {
        public WaterOff(long delayTime) { super(delayTime); }
        public void action() {
            // Put hardware control code here.
            water = false;
        }
        public String toString() {
            return "Greenhouse water is off";
        }
    }
    public class ThermostatNight extends Event {
        public ThermostatNight(long delayTime) {
            super(delayTime);
        }
        public void action() {
            // Put hardware control code here.
            thermostat = "Night";
        }
        public String toString() {
            return "Thermostat on night setting";
        }
    }
    public class ThermostatDay extends Event {
        public ThermostatDay(long delayTime) {
            super(delayTime);
        }
        public void action() {
            // Put hardware control code here.
            thermostat = "Day";
        }
        public String toString() {
            return "Thermostat on day setting";
        }
    }

    // An example of an action() that inserts a
    // new one of itself into the event list:
    public class Bell extends Event {
        public Bell(long delayTime) {
            super(delayTime);
        }

        public void action() {
            addEvent(new Bell(delayTime));
        }

        public String toString() { return "Bing!"; }
    }

    private boolean fans;

    public class FansOn extends Event {
        public FansOn(long delayTime) {
            super(delayTime);
        }

        public void action() {
            fans = true;
        }

        public String toString() {
            return "Fans are on";
        }
    }

    public class FansOff extends Event {
        public FansOff(long delayTime) {
            super (delayTime);
        }

        public void action() {
            fans = false;
        }

        public String toString() {
            return "Fans are off";
        }
    }

    private boolean windowork;

    public class WinidowMalfunction extends Event {
        public WinidowMalfunction(long delayTime) {
            super(delayTime);
        }

        public void action() {
            windowork = false;
        }
    }

    private boolean poweron;

    public class PowerOut extends Event {
        public PowerOut(long delayTime) {
            super(delayTime);
        }

        public void action() {
            poweron = false;
        }
    }

    public class ControllerException extends Exception {
        public ControllerEception(String except) {
            super(except);
        }

        public String getMessage() {
            return super.getMessage();
        }

        public void shutdown() {

        }
    }

    public class Restart extends Event {
        public Restart(long delayTime, String filename) {
            super(delayTime);
            eventsFile = filename;
        }

        public void action() {
            Scanner scanner = new Scanner(eventsFile);
            while(scanner.hasNextLine()) {
                String line = scanner.nextLine();
            }

            addEvent(new ThermostatNight(0));
            addEvent(new LightOn(2000));
            addEvent(new WaterOff(8000));
            addEvent(new ThermostatDay(10000));
            addEvent(new Bell(2000));
            addEvent(new WaterOn(6000));
            addEvent(new LightOff(4000));
            addEvent(new Terminate(12000));
            addEvent(new FansOn(5000));
            addEvent(new FansOff(1000));
        }

        public String toString() {
            return "Restarting system";
        }
    }

    public class Terminate extends Event {
        public Terminate(long delayTime) { super(delayTime); }
        public void action() { System.exit(0); }
        public String toString() { return "Terminating";  }
    }


    public static void printUsage() {
        System.out.println("Correct format: ");
        System.out.println("  java GreenhouseControls -f <filename>, or");
        System.out.println("  java GreenhouseControls -d dump.out");
    }

    //---------------------------------------------------------
    public static void main(String[] args) {
        try {
            String option = args[0];
            String filename = args[1];

            if ( !(option.equals("-f")) && !(option.equals("-d")) ) {
                System.out.println("Invalid option");
                printUsage();
            }

            GreenhouseControls gc = new GreenhouseControls();

            if (option.equals("-f"))  {
                gc.addEvent(gc.new Restart(0,filename));
            }

            gc.run();
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid number of parameters");
            printUsage();
        }
    }

} ///:~

Controller.java

package tme3;
import java.util.*;


public class Controller {
  // A class from java.util to hold Event objects:
  private List<Event> eventList = new ArrayList<Event>();
  public void addEvent(Event c) { eventList.add(c); }

  public void run() {
    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);
        }
  }
} ///:~

Event.java

package tme3;

import java.io.*;

public abstract class Event {
  private long eventTime;
  protected final long delayTime;
  public Event(long delayTime) {
    this.delayTime = delayTime;
    start();
  }
  public void start() { // Allows restarting
    eventTime = System.currentTimeMillis() + delayTime;
  }
  public boolean ready() {
    return System.currentTimeMillis() >= eventTime;
  }
  public abstract void action();
} ///:~

1 个答案:

答案 0 :(得分:0)

添加了代码注释以了解它。

GreenhouseControls.java

PageView, Swiper or liquid_swiper

Controller.java

package tme3;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class GreenhouseControls extends Controller {
    private boolean light = false;
    private boolean water = false;
    private String thermostat = "Day";
    private String eventsFile = "example1.txt";

    // 3. Add an instance variable in GreenhouseControls called error code.
    private int errorCode;

    public class LightOn extends Event {
        public LightOn(long delayTime) {
            super(delayTime);
        }

        public void action() {
            // Put hardware control code here to
            // physically turn on the light.
            light = true;
        }

        public String toString() {
            return "Light is on";
        }
    }

    public class LightOff extends Event {
        public LightOff(long delayTime) {
            super(delayTime);
        }

        public void action() {
            // Put hardware control code here to
            // physically turn off the light.
            light = false;
        }

        public String toString() {
            return "Light is off";
        }
    }

    public class WaterOn extends Event {
        public WaterOn(long delayTime) {
            super(delayTime);
        }

        public void action() {
            // Put hardware control code here.
            water = true;
        }

        public String toString() {
            return "Greenhouse water is on";
        }
    }

    public class WaterOff extends Event {
        public WaterOff(long delayTime) {
            super(delayTime);
        }

        public void action() {
            // Put hardware control code here.
            water = false;
        }

        public String toString() {
            return "Greenhouse water is off";
        }
    }

    public class ThermostatNight extends Event {
        public ThermostatNight(long delayTime) {
            super(delayTime);
        }

        public void action() {
            // Put hardware control code here.
            thermostat = "Night";
        }

        public String toString() {
            return "Thermostat on night setting";
        }
    }

    public class ThermostatDay extends Event {
        public ThermostatDay(long delayTime) {
            super(delayTime);
        }

        public void action() {
            // Put hardware control code here.
            thermostat = "Day";
        }

        public String toString() {
            return "Thermostat on day setting";
        }
    }

    // An example of an action() that inserts a
    // new one of itself into the event list:
    public class Bell extends Event {
        public Bell(long delayTime) {
            super(delayTime);
        }

        public void action() {
            addEvent(new Bell(delayTime));
        }

        public String toString() {
            return "Bing!";
        }
    }

    private boolean fans;

    public class FansOn extends Event {
        public FansOn(long delayTime) {
            super(delayTime);
        }

        public void action() {
            fans = true;
        }

        public String toString() {
            return "Fans are on";
        }
    }

    public class FansOff extends Event {
        public FansOff(long delayTime) {
            super(delayTime);
        }

        public void action() {
            fans = false;
        }

        public String toString() {
            return "Fans are off";
        }
    }

    private boolean windowork;

    public class WinidowMalfunction extends Event {

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

        // 1. After setting the variables, WindowMalfunction or PowerOut should throw an
        // exception specifying the faulty condition
        public void action() throws ControllerException {
            windowork = false;
            // 3. error code in an int variable error code -> 1 for WindowMalfunction
            someThingWentWrongHere(1, "Error at WinidowMalfunction");
        }

    }

    private boolean poweron;

    public class PowerOut extends Event {

        public PowerOut(long delayTime) {
            super(delayTime);

        }

        // 1. After setting the variables, WindowMalfunction or PowerOut should throw an
        // exception specifying the faulty condition
        public void action() throws ControllerException {
            poweron = false;
            // 3. error code in an int variable error code -> 2 for powerOut
            someThingWentWrongHere(2, "Error at powerOut event");
        }

    }

    void someThingWentWrongHere(int errorCode, String errorMessage) throws ControllerException {
        this.errorCode = errorCode;
        throw new ControllerException(errorMessage);
    }

    public class ControllerException extends Exception {
        public ControllerException(String except) {
            super(except);
        }

        public String getMessage() {
            return super.getMessage();
        }

        public void shutdown() {

        }
    }

    public class Restart extends Event {
        public Restart(long delayTime, String filename) {
            super(delayTime);
            eventsFile = filename;
        }

        public void action() {
            Scanner scanner = new Scanner(eventsFile);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
            }

            addEvent(new ThermostatNight(0));
            addEvent(new LightOn(2000));
            addEvent(new WaterOff(8000));
            addEvent(new ThermostatDay(10000));
            addEvent(new Bell(2000));
            addEvent(new WaterOn(6000));
            addEvent(new LightOff(4000));
            addEvent(new Terminate(12000));
            addEvent(new FansOn(5000));
            addEvent(new FansOff(1000));
        }

        public String toString() {
            return "Restarting system";
        }
    }

    public class Terminate extends Event {
        public Terminate(long delayTime) {
            super(delayTime);
        }

        public void action() {
            System.exit(0);
        }

        public String toString() {
            return "Terminating";
        }
    }

    public static void printUsage() {
        System.out.println("Correct format: ");
        System.out.println("  java GreenhouseControls -f <filename>, or");
        System.out.println("  java GreenhouseControls -d dump.out");
    }

    // ---------------------------------------------------------
    public static void main(String[] args) {
        GreenhouseControls gc = new GreenhouseControls();

        try {
            /*
             * String option = args[0]; String filename = args[1];
             * 
             * if (!(option.equals("-f")) && !(option.equals("-d"))) {
             * System.out.println("Invalid option"); printUsage(); }
             * 
             * if (option.equals("-f")) { gc.addEvent(gc.new Restart(0, filename)); }
             */

            // UnCommenting above code will never test below code because above code with
            // throw first exception and it will never execute below code

            // To test PowerOut fail with exception
            // gc.addEvent(gc.new PowerOut(100));

            // To test WinidowMalfunction fail with exception
            gc.addEvent(gc.new WinidowMalfunction(100));

            gc.run();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid number of parameters");
            printUsage();
        }
        // 2. the Controller catches the exception
        catch (ControllerException e) {
            // 2. then initiates an emergency shutdown with an appropriate message
            gc.shutdown(e.getMessage());
        }

    }

    // override this method in GreenhouseControls to accomplish the shutdown.
    @Override
    protected void shutdown(String message) {
        // super.shutdown();
        DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
        Date dateobj = new Date();

        // logs the time and the reason for the shutdown in a text file ,, Here you will
        // create file and log it
        System.out.println("Shutdown due to Error: " + message + " | Error Code:" + errorCode + " | DateTime:" + df.format(dateobj));
    }

    /*
     * enum ErrorCode { WindowMalfunction, PowerOut }
     */
}

Event.java

package tme3;

import java.util.*;

import tme3.GreenhouseControls.ControllerException;

public class Controller {
    // A class from java.util to hold Event objects:
    private List<Event> eventList = new ArrayList<Event>();

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

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

    //2. Add a method to Controller called shutdown,
    protected void shutdown(String message) {
        System.out.println("ShutDown from controller");
    }
}