【发布时间】: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 loop和entire循环没有被执行。这怎么失败?当我执行 addResult() 时,它会将我带到Api.java并检查if(status != 200),如我原来的问题所示。然后我把 ApiException 扔在那里。 addResult() 调用不在 Api.java 中。 -
更新我的问题
标签: java exception try-catch throw