我应该在 if-else 块中抛出异常吗?

新手上路,请多包涵

这是代码:

 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 许可协议

阅读 429
2 个回答

在 try 块中抛出异常并立即捕获它是没有意义的,除非 catch 块抛出不同的异常。

这样你的代码会更有意义:

 public Response getABC(Request request) {
    Response res = new Response();
    if (request.someProperty == 1) {
        // business logic
    } else {
        res.setMessage("xxxx");
    }
    return res;
}

如果您的业务逻辑(在条件为 true 时执行)可能抛出异常,则只需要 try-catch 块。

如果您没有捕获异常(这意味着调用者必须处理它),您可以不使用 else 子句:

 public Response getABC(Request request) throws Exception {
    if (request.someProperty != 1) {
        throw new Exception("xxxx");
    }

    Response res = new Response();
    // business logic
    return res;
}

原文由 Eran 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你从方法中抛出异常那么为什么要捕获它呢?要么你返回一个带有“xxxx”消息的响应,要么抛出一个异常让这个方法的调用者处理它。

 public Response getABC(Request requst) {
    Response res = new Response();
        if(request.someProperty == 1){
            //business logic
        else{
           res.setMessage("xxxx");
        }
    }
    return res;
}

或者

public Response getABC(Request requst) throw Excetpions {
    Response res = new Response();
        if(request.someProperty == 1){
            //business logic
        else{
           throw new Exception("xxxx");
        }
    return res;
}

public void someMethod(Request request) {
    try {
        Response r = getABC(request);
    } catch (Exception e) {
        //LOG exception or return response with error message
        Response response = new Response();
        response.setMessage("xxxx");
        retunr response;
    }

}

原文由 mkjh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题