我在类中有如下两种方法
// this method doesn't return anything.
void X(){
try{operation1}
catch(SpecificException1 e1){do something}
catch(SpecificException2 e2){do something}
catch(SpecificException3 e3){do something}
}
// this method return an object.
Object Y(){
try{operation2}
catch(SpecificException1 e1){do something}
catch(SpecificException2 e2){do something}
catch(SpecificException3 e3){do something}
return object;
}
我尝试通过以下方式重构它:
// this method doesn't return anything.
void X(){
try{operation1}
catch(Exception e){handle(e)}
}
// this method return an object.
object Y(){
try{operation2}
catch(Exception e){handle(e)}
return object;
}
handle(Exception e){
try{ throw e}
catch(SpecificException1 e1){do something}
catch(SpecificException2 e2){do something}
catch(SpecificException3 e3){do something}
catch(Exception e){do something}
}
但是我告诉过捕获一般异常不是一个好的代码实践,因为我在方法 X 和 Y 中捕获一般异常。但是根据我的思维过程,虽然我在 X 和 Y 方法中捕获一般异常,但我正在处理特定的异常捕获特定异常的“handle”方法中的异常。
我无法弄清楚这种方法有什么问题。在我看来,它增加了代码的可读性。在单独的方法中进行相同的捕获将使代码的可读性稍差。如果我在类中有 3-4 个具有相同类型捕获的方法,这将变得更加乏味。
如果您有不同的方法来处理此类情况,请提出建议。
最佳答案
更好的解决方案是定义一个通用的功能命令接口(interface)并将其传递给执行命令并处理异常的方法:
public interface Command<R> {
R execute() throws SpecificException1, SpecificException2, SpecificException3;
}
...
public void x() {
this.execute(() -> operation1());
}
public SomeObject y() {
return this.execute(() -> operation2()).orElse(someDefaultValue);
}
private <R> Optional<R> execute(Command<R> command) {
try {
return Optional.ofNullable(command.execute());
}
catch(SpecificException1 e) {
doSomething();
}
catch(SpecificException2 e) {
doSomethingElse();
}
catch(SpecificException3 e) {
doYetAnotherThing();
}
return Optional.empty();
}
当然,这应该适合您的实际用例。忽略异常对我来说看起来很奇怪。如果您确实想传播它们,则不需要这个可选的东西,并且每个异常处理方法只会抛出一个运行时异常。
关于java - 通过在不同方法中处理异常来重构代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53582203/