简体   繁体   English

用自定义消息替换Java抛出异常,然后继续

[英]Replace Java throw exception with custom message and continue

My Java for loop checks for different id in ids() String[] array as: 我的Java for loop ids() String[] array其他id检查为:

BackTest.java BackTest.java

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

where addResult() is adding the result to some Java map . 其中addResult()将结果添加到某些Java map Here if the id does not exist , ie http status!=200 then I am throwing a new exception as shown in the following snippet: 如果id does not exist ,即http status!=200那么我将抛出一个新异常,如以下代码片段所示:

Api.Java 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 + ")"
                            );
       }

Now in my first for loop, if the first id in the loop does not exist , then I am throwing an exception and this makes my entire process to fail and it fails to check for the further ids as a part of id array . 现在在我的第一个for循环中,如果循环中的第一个id does not exist ,那么我将引发异常,这会使my entire process to fail ,并且无法further ids as a part of id array来检查further ids as a part of id array How do I make sure that even if it fails on first id in an array, code should continue to check for further ids? 我如何确保即使在数组的第一个ID失败时,代码也应继续检查其他ID?

I can think of replacing throw new exception with try-catch block. 我可以考虑用try-catch块替换throw new exception An example would be good. 一个例子会很好。

You can handle an exception like so; 您可以像这样处理异常;

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

This will catch the exception, which stops it from propagating past this point and therefore ending the loop, and it will print a message and the stack trace instead. 这将捕获异常,这将阻止异常传播到该点之外,从而结束循环,并且它将打印一条消息和堆栈跟踪。

If you would like to continue processing the rest of your list/array without the overhead of throwing a new exception, then I would look into using the continue keyword. 如果您想继续处理列表/数组的其余部分而没有引发新异常的开销,那么我将考虑使用continue关键字。

The continue keyword was designed for situations like this. continue关键字是针对此类情况设计的。 It causes the program's execution to immediately return to the start of the closest loop and test its condition. 它使程序的执行立即返回最接近的循环的开始并测试其条件。 I would suggest using the following setup. 我建议使用以下设置。

    for(String id : ids()) {

        //do stuff...

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

        addResult(result(id));
    }

Some do not like using continue as too many of them can generate messy code. 有些人不喜欢使用continue ,因为它们太多会生成混乱的代码。 However, if used sparingly, they can help cut down on the amount of code within a loop. 但是,如果谨慎使用,它们可以帮助减少循环中的代码量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM