【发布时间】:2015-02-11 23:12:50
【问题描述】:
我有一个 ProductionWorker 类和超类 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;
}
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;
}
当我尝试编译时,出现以下错误:
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
现在,实际的异常本身是在 getShift() 方法中抛出的,因此 Employee.toString() 方法实际上不可能抛出异常。该程序将进入 ProductionWorker.toString(),运行 Employee.toString() 并返回它的字符串,然后稍后执行 getShift(),这可能抛出异常。所以我不需要 Employee.toString() 能够抛出,如果这样做会导致其他问题。
有什么帮助吗?
编辑
我将把整个东西重写为一个 int 而不是两个布尔值。
【问题讨论】:
-
嗯...
toString()方法实际上不会抛出InvalidShift异常,所以你不应该声明它会,就这么简单。 -
InvalidShift 是自定义异常类,不是抛出异常的方法。
-
我的错误。底线是:toString() 不应该被写成抛出任何异常。期间
-
对于初学者,即使这是自定义异常类,也请遵守约定并适当命名:
InvalidShiftException等 -
那么我应该在哪里抛出异常?我不能在 setShift() 方法中使用它,因为默认运行 setShift 方法会将 shiftValid 设置为 true。基本上我有两个布尔变量:dayShift 和 shiftValid。如果从未运行 setShift(),则 shiftValid 将为 false,如果有人尝试 getShift(),则应抛出异常。如果 dayShift 为 true,则表示此人从事白班工作,如果为 false,则表示此人上夜班。有意义吗?
标签: java exception methods superclass custom-exceptions