Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
im_mangesh Avatar asked Jan 19 '18 10:01

im_mangesh


People also ask

How do you continue a loop after catching exception in try catch?

As you are saying that you are using try catch within a for each scope and you wants to continue your loop even any exception will occur. So if you are still using the try catch within the loop scope it will always run that even exception will occur. it is upto you how you deal with exception in your way.

Does Java continue after exception?

Resuming the program When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.

How do you handle exceptions in a for loop in Java?

Read the inputs and perform the required calculations within a method. Keep the code that causes exception in try block and catch all the possible exceptions in catch block(s). In each catch block display the respective message and call the method again.


2 Answers

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.

like image 153
Maltanis Avatar answered Sep 20 '22 16:09

Maltanis


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
}
like image 31
Murat Karagöz Avatar answered Sep 19 '22 16:09

Murat Karagöz