这是代码:
public Response getABC(Request request) throws Exception {
Response res = new Response();
try {
if (request.someProperty == 1) {
// business logic
} else {
throw new Exception("xxxx");
}
} catch (Exception e) {
res.setMessage(e.getMessage); // I think this is weird
}
return res;
}
这个程序工作正常。我认为它应该重新设计,但是如何呢?
原文由 Lauda Wang 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 try 块中抛出异常并立即捕获它是没有意义的,除非 catch 块抛出不同的异常。
这样你的代码会更有意义:
如果您的业务逻辑(在条件为
true
时执行)可能抛出异常,则只需要 try-catch 块。如果您没有捕获异常(这意味着调用者必须处理它),您可以不使用
else
子句: