Continue executing loop after catching an exception in try/catch block

3.2k views Asked by At

How to continue the iteration loop if an exception occurs at while (iterator.hasNext())?

So I want to do something like below.

            try {
                loop: while (iterator.hasNext())  // as excetion is on this line excetion will be catch by catch_2
                {
                    try {
                        Result res = (Result) iterator.next();
                        list.add(res);
                    } catch (Exception e) {                    // catch_1
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {                            // catch_2
                // goto start of the loop
                continue loop;
            }

Iterator<UserProvisioning> iterator = beans.iterator();
            while (iterator.hasNext()) {
                try {
                    UserProvisioning userProvisioning = (UserProvisioning) iterator.next();
                    System.out.println(userProvisioning.getFIRST_NAME());
                    list.add(userProvisioning);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    logger.error("Error occured...)
                }
            }

As per my understanding iterator.hasNext() tries to check whether next element is present or not by mapping csv record column to POJO fields and as there is invalid data in csv record headers count do not matches record files hence error

java.lang.RuntimeException: com.opencsv.exceptions.CsvRequiredFieldEmptyException: Number of data fields does not match number of headers.

SO I am trying to log the error and continue to iterate next records.

EDIT iterator.hasNext() should return true or false but its throwing error

1

There are 1 answers

3
locus2k On

If you put a try-catch block within your loop it will continue the loop to the end unless you break out of it

for(Iterator<UserProvisioning> iter = beans.iterator(); iter.hasNext();) {
  try{
    UserProvisioning userProvisioning = iter.next();
    System.out.println(userProvisioning.getFIRST_NAME());
    list.add(userProvisioning);
  } catch(Exception ex) {
    logger.warn("An issue occurred when looping through user provisionings: " + ex.getMessage());

  }
}

The above code will setup an iterator and loop through it. If an exception occurs it will log and continue the loop since no break was called.

also since you tell what type the iterator is, there is no need to cast it when you call iter.next()