基础异常/h3>
我有许多类型异常,它们都具有相同的特征:它们持有一个总是非零的状态(int)字段。代码通常检查状态变量,如果非零则抛出相应的异常(取决于上下文)。例如:
if (status != 0) throw new AStatusException(status);
... // other context
if (status != 0) throw new BStatusException(status);
... // other context
if (status != 0) throw new CStatusException(status);
主要是出于好奇,我想我可以在一个基类StatusException
的静态方法throwIfNotZero
中实现这个常见的功能,并让各种A, B, CStatusException
类都继承这个类。这将允许我编写这样的代码:
AStatusException.throwIfNonZero(status);
... // other context
BStatusException.throwIfNonZero(status);
... // other context
CStatusException.throwIfNonZero(status);
遗憾的是,我得到的最接近的是我在帖子末尾附加的代码,这不是很令人满意。有没有更好的方法来做到这一点,也许不使用反射和/或避免要求传递类实例,这似乎是多余的(见"用法")?
<基础异常/h3>import java.lang.reflect.InvocationTargetException;
public class StatusException extends Exception {
public int status;
public StatusException (int status) {
this.status = status;
}
public static <T extends StatusException> void raiseIfNotZero(Class<T> klass, int code) throws T{
try {
if (code != 0) throw klass.getConstructor(Integer.TYPE).newInstance(code);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
用法:
AStatusException.raiseIfNotZero(AStatusException.class, status);
BStatusException.raiseIfNotZero(BStatusException.class, status);
import java.lang.reflect.InvocationTargetException;
public class StatusException extends Exception {
public int status;
public StatusException (int status) {
this.status = status;
}
public static <T extends StatusException> void raiseIfNotZero(Class<T> klass, int code) throws T{
try {
if (code != 0) throw klass.getConstructor(Integer.TYPE).newInstance(code);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
AStatusException.raiseIfNotZero(AStatusException.class, status);
BStatusException.raiseIfNotZero(BStatusException.class, status);
可以在超类StatusException中重载函数raiseIfNotZero()。
然后这样命名
StatusException.raiseIfNotZero(AStatusException.class, status);
StatusException.raiseIfNotZero(BStatusException.class, status);
public static int final STATUS_EXCEPTION_A=1;
public static int final STATUS_EXCEPTION_A=2;
raiseIfNotZero(int type, int status)
{
switch(type)
{ case STATUS_EXCEPTION_A: throw new AStatusException(); break;
case STATUS_EXCEPTION_B: throw new BStatusException(); break;
...
}
}