PMD 报告“正在对捕获的异常执行 instanceof 检查。为此异常类型创建一个单独的 catch 子句。”对于下面的代码。
String parameter;
try {
...
} catch (Exception e) {
logFailure(e, parameter);
if (e instanceof X) {
throw new A(e);
} else if (e instanceof Y
|| e instanceof Z) {
throw new B(e);
}
throw new InternalServerErrorException(e);
}
如果我将上面的代码更改为下面的代码,logFailure(e) 有 3 个重复,是否有更好的方法来消除这种 PMD 违规?
String parameter;
try {
...
} catch (X e) {
logFailure(e, parameter);
throw new A(e);
} catch (Y e) {
logFailure(e);
throw new B(e);
} catch (Z e) {
logFailure(e);
throw new B(e);
} catch (exception e) {
logFailure(e);
throw new InternalServerErrorException(e);
}
最佳答案
String parameter;
try {
...
} catch (Exception e) {
logFailure(e, parameter);
throwException(e);
}
public void throwException(Exception e) throws Exception{
if (e instanceof X) {
throw new A(e);
} else if (e instanceof Y
|| e instanceof Z) {
throw new B(e);
}
throw new InternalServerErrorException(e);
}
此外,您可以将Logger
移动到此方法
,具体取决于您的设计/应用
关于Java:如何重构这种try-catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17742219/