Pratik Jaiswal
Pratik Jaiswal

Reputation: 299

Replace Java throw exception with custom message and continue

My Java for loop checks for different id in ids() String[] array as:

BackTest.java

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

where addResult() is adding the result to some Java map. Here if the id does not exist, i.e http status!=200 then I am throwing a new exception as shown in the following snippet:

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. How do I make sure that even if it fails on first id in an array, code should continue to check for further ids?

I can think of replacing throw new exception with try-catch block. An example would be good.

Upvotes: 0

Views: 2447

Answers (2)

Alex A
Alex A

Reputation: 368

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.

The continue keyword was designed for situations like this. 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. However, if used sparingly, they can help cut down on the amount of code within a loop.

Upvotes: 0

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.

Upvotes: 2

Related Questions