im_mangesh
im_mangesh

Reputation: 175

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?

Upvotes: 7

Views: 20271

Answers (4)

Jeroen Steenbeeke
Jeroen Steenbeeke

Reputation: 4013

Technically, it's simply a matter of catching the exception (see Murat K's answer). I would recommend, however, that since you're sending e-mail, that you do cease sending the rest when the first exception occurs, unless you are certain that it is an error you can safely ignore. A few examples of things that can go wrong:

  • Invalid credentials: this means that if you continue attempting to send, every subsequent attempt will also fail. Best case: no e-mail sent. Worst case: SMTP server blocks your access due to excessive login failures.
  • Malformed recipient address: no issue to continue trying the other addresses, but you need to do something with this error (remove recipient from list for future mailings)
  • Misconfigured mail server address: each iteration of your loop will try to connect to the mailserver, and fail. This will slow down the method tremendously (server timeouts) or spam your log (assuming you did something with the exception)

So please consider your course of action carefully when handling e-mail.

Upvotes: 4

Maltanis
Maltanis

Reputation: 523

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.

Upvotes: 9

Umair Mohammad
Umair Mohammad

Reputation: 4635

You can try something like this

if (Recipients_To != null) {
    for (int i = 0; i < Recipients_To.length; i++) {
        try {
            message.setRecipients(Message.RecipientType.TO, Recipients_To[i].toString());
            Transport.send(message);
        } catch (Exception exp) {
            //Log your exception here or do whatever you want to happen in case of exception
        }
    }
}

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

You can catch the exception e.g.

try {
    message.setRecipients(Message.RecipientType.TO, Recipients_To[i].toString());
    Transport.send(message);
} catch (Exception e) {
    // handle it or leave it be
}

Upvotes: 5

Related Questions