Search code examples
javajakarta-mail

Continue for loop after exception java


This is my code:

if (Recipients_To != null) {
    for (int i = 0; i < Recipients_To.length; i++) {
        message.setRecipients(Message.RecipientType.TO, Recipients_To[i].toString());
        Transport.send(message);
    }
}

I have more than 500 Recipients list to send mail and this code will send personal mail to each recipients. But if i got exception in between this for loop i want to continue loop for remaining recipients. How can i do?


Solution

  • You want to use try catch blocks to do this, like so

    for (int i = 0; i < Recipients_To.length; i++) 
    {
        try {
           message.setRecipients(Message.RecipientType.TO,Recipients_To[i].toString());
           Transport.send(message);
        }
        catch (YourException e){
           //Do some thing to handle the exception
        }
    }
    

    This catches the potential issue and will still continue with the for loop once the exception has been handled.