我应该在 if-else 块中引发异常吗?

2022-09-01 06:24:54

代码如下:

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;
}

此程序工作正常。我认为它应该重新设计,但如何重新设计呢?


答案 1

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

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

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

仅当业务逻辑(在条件为 时执行)可能引发异常时,才需要 try-catch 块。true

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

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

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

答案 2

如果您要从该方法中抛出异常,那么为什么要费心捕获它?它要么返回带有“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;
    }

}