Search code examples
javaexceptiontry-catchthrow

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.


Solution

  • 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.