我想编写一个可用于不同类和特定行为的异常类。它适用于更改对象 - 比如
a.setWeight(500)
- 但它在我的构造函数中不起作用 - 比如
Cheese b = new Cheese(500);
因为没有生成对象,并且在我的 WeightException 中插入了 null。
public class WeightException extends Exception {
private int attribute;
private Object object;
public WeightException(Object o, int a) throws WeightException {
object = o;
attribute = a;
}
public String getMessage() {
if(object instanceof Cheese)
return "Cheese is overweight.";
if(object instanceof Baggage)
return "Baggage is "+String.valueOf(attribute)+" kilos overweight.";
}
}
public class Cheese {
private int weight;
public Cheese(int weight) {
setWeight(weight);
}
public void setWeight(int weight) throws WeightException {
if(weight<200)
this.weight = weight;
else
throw new WeightException(this, weight);
}
}
有没有人知道比在我的异常类参数中插入带有类名的字符串更好的方法来解决这个问题?