代码如下:
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;
}
这个程序运行良好。 我认为它应该重新设计,但如何?
最佳答案
在 try block 中抛出异常并立即捕获它是没有意义的,除非 catch block 抛出不同的异常。
这样你的代码会更有意义:
public Response getABC(Request request) {
Response res = new Response();
if (request.someProperty == 1) {
// business logic
} else {
res.setMessage("xxxx");
}
return res;
}
如果您的业务逻辑(当条件为 true
时执行)可能会抛出异常,您只需要 try-catch block 。
如果你没有捕捉到异常(这意味着调用者必须处理它),你可以不使用 else
子句:
public Response getABC(Request request) throws Exception {
if (request.someProperty != 1) {
throw new Exception("xxxx");
}
Response res = new Response();
// business logic
return res;
}
关于java - 我应该在 if-else block 中抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53941088/