假设我有一个抽象类Base,它有一个具体的方法execute和三个抽象方法stepOne、stepTwo和stepThree……
public abstract class Base {
protected abstract void stepOne();
protected abstract void stepTwo();
protected abstract void stepThree();
public final void execute() {
//do stuff
stepOne();
//do stuff
stepTwo();
//do stuff
stepThree();
//do stuff
}
}...and由一个具体的类Sub1子类
public class Sub1 extends Base {
protected void stepOne() {
//...
}
protected void stepTwo() {
//...
}
protected void stepThree() {
//...
}
}现在假设我有第二个子类Sub2,它可以在stepOne和stepTwo中抛出一个检查过的异常
public class Sub2 extends Base {
protected void stepOne() throws Exception1 {
//...
}
protected void stepTwo() throws Exception2 {
//...
}
protected void stepThree() {
//...
}
}我想按以下方式使用这些课程:
Sub1 s1 = new Sub1();
try {
s1.execute();
} catch (Exception1 e1) {
//handle e1
} catch (Exception2 e2) {
//handle e2
}
Sub2 s2 = new Sub2();
s2.execute();显然,这是不起作用的,因为Base中的方法在任何例外情况下都不会声明。
如何在实现类中任意抛出异常?是否有一种方法不需要使用execute声明throws Exception,并且总是需要尝试捕获呢?我还想避免将execute中的公共逻辑复制到它的子类中。这里最好的解决方案是什么?有更好的设计模式吗?
发布于 2020-09-23 11:19:04
下面是如何通过使Base类方法抛出泛型异常来解决这个问题:
public abstract class Base<E1 extends Exception, E2 extends Exception, E3 extends Exception> {
protected abstract void stepOne() throws E1;
protected abstract void stepTwo() throws E2;
protected abstract void stepThree() throws E3;
public final void execute() throws E1, E2, E3 {
//do stuff
stepOne();
//do stuff
stepTwo();
//do stuff
stepThree();
//do stuff
}
}通过扩展Base<RuntimeException, RuntimeException, RuntimeException>,您可以创建一个不引发任何检查异常的子类,如下所示:
public class Sub1 extends Base<RuntimeException, RuntimeException, RuntimeException> {
protected void stepOne() {
//...
}
protected void stepTwo() {
//...
}
protected void stepThree() {
//...
}
}下面是如何创建一个子类,该子类可以在某些步骤中抛出检查过的异常:
public class Sub2 extends Base<Exception1, Exception2, RuntimeException> {
protected void stepOne() throws Exception1 {
//...
}
protected void stepTwo() throws Exception2 {
//...
}
protected void stepThree() {
//...
}
}您可以按以下方式使用这些类:
Sub2 s2 = new Sub2();
try {
s2.execute();
} catch (Exception1 e1) {
//handle e1
} catch (Exception2 e2) {
//handle e2
}
Sub1 s1 = new Sub1();
s1.execute();https://stackoverflow.com/questions/63870971
复制相似问题