将 Java throw exception 替换为自定义消息并继续

Replace Java throw exception with custom message and continue

我的 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,那么我将抛出一个新的异常,如以下代码片段所示:

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。举个例子就好了。

你可以像这样处理异常;

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

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

如果您想继续处理 list/array 的其余部分而不需要抛出新异常的开销,那么我会考虑使用 continue 关键字。

continue 关键字就是为这种情况设计的。它会导致程序的执行立即 return 到最近循环的开始并测试其条件。我建议使用以下设置。

    for(String id : ids()) {

        //do stuff...

        if(status != 200) {
            //write to data logger, etc...
            continue;
        }

        addResult(result(id));
    }

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