[英]Java: How to refactor this kind of try-catch block?
PMD报告“正在对捕获的异常执行检查实例。为此异常类型创建单独的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);
}
如果我将上面的代码改为下面,有3个重复的logFailure(e),有没有更好的方法来消除这种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
移动到此method
,具体取决于您的设计/应用程序
你可以这样做:(使用外部尝试捕获)
String parameter;
try {
try {
...
} catch (Exception e) {
logFailure(e, parameter);
throw e;
}
} catch (X e) {
throw new A(e);
} catch (Y e) {
throw new B(e);
} catch (Z e) {
throw new B(e);
} catch (exception e) {
throw new InternalServerErrorException(e);
}
}
你可以做这样的事情
try{
// do some thing
} catch (X |Y |Z | Exception e) {
logFailure(e, parameter);
throw new Exception(e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.