我无法让我的方法抛出自定义异常

D. *_*ggs 0 java methods exception custom-exceptions superclass

我有一个类EmployWorker和我为学校项目创建的超类Employee.我们应该在本周为它设置例外,并且在尝试创建其中一个时我一直收到错误.这是我的代码:

在ProductionWorker中:

   public String toString() throws InvalidShift{
      DecimalFormat dollar = new DecimalFormat("$#,##0.00");
      String str = super.toString();

      str += "The employee's pay rate is " + dollar.format(getPayRate()) +"\n";
      str += "The employee works the " + getShift() + " shift";
      return str;
   }
Run Code Online (Sandbox Code Playgroud)

super.toString类:

   public String toString() throws InvalidShift{
      String str = "The employee's name is " + getEmployeeName() + ".\n";
      if (employeeNumber.equals("")){
         str += "The employee's ID number is invalid.\n";
      }else{
         str += "The Employee's ID number is " + employeeNumber + ".\n";
      }
      str += "The employee's hire date was " + hireDate + ".\n";

      return str;
   }
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我收到以下错误:

Employee.java:126: error: toString() in Employee cannot override toString() in Object
   public String toString() throws InvalidShift{
                 ^
  overridden method does not throw InvalidShift
ProductionWorker.java:54: error: toString() in ProductionWorker cannot override toString() in Object
   public String toString() throws InvalidShift{
                 ^
  overridden method does not throw InvalidShift
Run Code Online (Sandbox Code Playgroud)

现在,实际异常本身在getShift()方法中抛出,因此Employee.toString()方法无法实际抛出异常.程序将进入ProductionWorker.toString(),运行Employee.toString()并返回它的字符串,然后执行getShift(),这可能会抛出异常.所以我不需要Employee.toString()能够抛出,如果有的话,它会导致其他问题.

有帮助吗?

编辑

我将重写整个事件而不是两个布尔值.

Hov*_*els 6

底线是这样的:不应该写toString()来抛出任何异常.Period它唯一的工作是创建一个表示对象状态的String.它不应该改变对象本身的状态,它永远不需要抛出异常.

因此,摆脱throws InvalidShifttoString().

相反,将此语句添加到实际上可能抛出异常的方法.

你说:

现在,实际异常本身在getShift()方法中抛出,

所以应声明此方法抛出异常.

所以Employee.toString()方法无法实际抛出异常.

对.所以它不应该像你在代码中那样被声明为抛出它.

程序将进入ProductionWorker.toString(),运行Employee.toString()并返回它的字符串,然后执行getShift(),这可能会抛出异常.所以我不需要Employee.toString()能够抛出,如果有的话,它会导致其他问题.

那么为什么要声明它首先抛出异常呢?


是的,重命名为InvalidShiftException.


更多

我无法在setShift()方法中使用它,因为默认情况下运行setShift方法会将shiftValid设置为true.基本上我有两个布尔变量:dayShift和shiftValid.如果从不运行setShift(),则shiftValid将为false,并且如果有人关注getShift(),则应抛出异常.

然后getShift()应该声明抛出异常,实际上应该抛出它,如果有人在对象处于无效状态时调用它(如果setShift()没有被调用的话).

例如,

public Shift getShift() thows InvalidShiftException {
   if (!shiftValid) {
      throw new InvalidShiftException("maybe some text in here");
   } else {
      return whatIsSupposedToBeReturned;
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑
你说:

问题是toString()调用getShift(),因此抛出异常时toString()将在堆栈中.没有解决这个问题.

就在这里!在toString()中使用try/catch!或者在调用getShift()内部之前先测试shift是否有效(调用一个布尔方法)toString()