【问题标题】:Replace Java throw exception with custom message and continue用自定义消息替换 Java 抛出异常并继续
【发布时间】:2016-06-14 22:39:56
【问题描述】:

我的 Java for loop 检查 ids() String[] array 中的不同 id 为:

BackTest.java

.....
    for (String id: ids()) {
         //..do something
         addResult(result(id));
    }

addResult() 将结果添加到一些 Java map。这里如果id does not exist,即http status!=200,那么我将抛出一个新异常,如下面的sn-p所示:

Api.Java

......
     if (status != 200) {
                    String error = "No additional error message received";
                    if (result != null && result instanceof JSONObject) {
                        JSONObject obj = (JSONObject) result;
                        if (obj.containsKey("error")) {
                            error = '"' + (String) obj.get("error") + '"';
                        }
                    }

                    throw new ApiException(
                            "API returned HTTP " + status +
                            "(" + error + ")"
                            );
       }

现在在我的第一个 for 循环中,如果循环中的第一个 id does not exist,那么我将抛出一个异常,这使得 my entire process to fail 并且它无法检查 further ids as a part of id array。我如何确保即使它在数组中的第一个 id 上失败,代码也应该继续检查更多的 id?

我可以考虑用 try-catch 块替换 throw new exception。举个例子就好了。

【问题讨论】:

  • 您可以捕获异常并使用try/catch 处理它们。你问的是这个吗?
  • 是的,你是对的。
  • 所以:try {addResult(result(id));} catch(ApiException e) {e.printStackTrace();}?
  • 不回答我的问题。所以,addResult() method is failing for first id in the loopentire 循环没有被执行。这怎么失败?当我执行 addResult() 时,它会将我带到 Api.java 并检查 if(status != 200),如我原来的问题所示。然后我把 ApiException 扔在那里。 addResult() 调用不在 Api.java 中。
  • 更新我的问题

标签: java exception try-catch throw


【解决方案1】:

你可以这样处理异常;

for(String id : ids()) {
    try {
        addResult(result(id));
    } catch(ApiException e) {
        System.err.println("Oops, something went wrong for ID "+id+"! Here's the stack trace:");
        e.printStackTrace();
    }
}

这将捕获异常,阻止它传播到此点并因此结束循环,并且它将打印一条消息和堆栈跟踪。

【讨论】:

    【解决方案2】:

    如果您想继续处理列表/数组的其余部分而无需引发新异常的开销,那么我会考虑使用 continue 关键字。

    continue 关键字专为此类情况而设计。它使程序的执行立即返回到最近循环的开始并测试其条件。我建议使用以下设置。

        for(String id : ids()) {
    
            //do stuff...
    
            if(status != 200) {
                //write to data logger, etc...
                continue;
            }
    
            addResult(result(id));
        }
    

    有些人不喜欢使用continue,因为太多会产生混乱的代码。但是,如果谨慎使用,它们可以帮助减少循环中的代码量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-28
      • 2011-09-18
      • 2023-03-05
      • 1970-01-01
      • 2021-05-13
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多