gpt4 book ai didi

java - 处理多个异常但避免重复代码

转载 作者:行者123 更新时间:2023-12-01 18:37:12 26 4
gpt4 key购买 nike

我想了解有关如何处理异常并仍然避免重复代码的意见。这是我处理这种情况的想法。

避免重复代码的情况(我不喜欢在这里使用instanceof)。

try{

//some code which might throw multiple different exceptions.

} catch(Exception e) {

//do something here

if(e instanceof IOException) {
// do something only when this type exception occurred.
} else if( e instanceof SQLException){
// do something only when this type of exception occurred.
} else if( e instanceof SomeCustomExceptionMaybe){
// do something only when this type of exception occurred.
}

//continue exception handling here.
}

对比

没有实例的情况(我真的不喜欢有重复的代码)。

try{

//some code which might throw multiple different exceptions.

} catch(IOException e1) {
// The order must always be this.
// do something general for each exception
// do something only with this exception
// do something general again.
} catch(SomeCustomExceptionMaybe e2) {
// The order must always be this.
// do something general for each exception
// do something only with this exception
// do something general again.
} //and so on

ps:给出答案时尽量避免 java 7 异常处理:

catch(IOException | SomeOtherTypeException | AnotherTypeException)

编辑:我没有使用 java 7,这就是为什么我要求避免基于 java 7 的响应。

最佳答案

第一个显而易见的解决方案是使用方法:

catch(IOException e1) {
doSomethingGeneral();
// do something only with this exception
doSomethingGeneralAgain();
}

但这留下了一些重复。以冗长为代价,由于 Java 还没有 lambda(但在 Java 8 中将会),您可以提取某些匿名类中的特定行为:

catch(IOException e1) {
handleException(new Runnable() {
@Override
public void run() {
// do something only with this exception
}
});
}

handleException() 的工作方式如下:

private void handleException(Runnable specificBehavior) {
// do something general
specificBehavior.run();
// do something general again
}

我已经等不及 Java 8 了,它将允许将其重写为:

catch(IOException e1) {
handleException(() -> {
// do something specific
});
}

关于java - 处理多个异常但避免重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21457491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com