我想编写一个可用于不同类和特定行为的异常类。它适用于更改对象,例如
a.setWeight(500)
-但它在我的构造函数中不起作用-就像
Cheese b = new Cheese(500);
因为未生成对象,并且 null 被插入到我的 WeightException 中。
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);
}
}
除了在异常类参数中插入带有类名的字符串之外,有人知道解决此问题的更好方法吗?
最佳答案
- 在要使用此异常的类中实现接口(interface)。
- 该接口(interface)有一个方法来定义消息,也可能有另一个方法来提供属性。
- 或者,提供属性数组并使用
String.format
构建消息。 - 使用该接口(interface)来定义传递给异常构造函数的对象参数。
- 在异常中调用该方法来获取消息。
就我个人而言,我发现这是一种反模式,除非您想要与异常一起使用的类非常紧密相关。否则,您将放弃具有语义意义的异常属性名称。
我宁愿看到一个特定于应用程序的父类(super class),其子类具有语义意义。
关于java - 不同类的对象的异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17116548/