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

标签 java if-statement exception throw

代码如下:

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/

相关文章:

java - 未找到 JSP、EL 属性

java - 如何让我的微调器与我的 EditText 具有相同的宽度?

linux - 否定 bash 脚本中的 if 条件

c# - 找不到这个 NullReferenceException 的原因

android - 从json中插入数据查询时出现sqlite异常?

java - 如何为 Ant 指定不同的 build.properties 路径?

java - 无法通过级联一键连接两个文件

asp.net - 如何在没有冗余的情况下更新/编辑asp.net mvc 5中上传的文件?

java - 将结果打印为 : ax+b = 0 线性方程的程序

java - 为什么说: "Checked exceptions are not forwarded in calling chain (propagated)"?