n0obiscuitz
n0obiscuitz

Reputation: 573

Is it possible to iterate again in a loop when catch an exception instead of continue?

Sorry if my title is a little bit confusing.

My program is doing some web scraping and thus will catch a few SocketTimeoutException due to random network conditions. Right now when the SocketTimeoutException is caught, that particular loop is skipped, and therefore i will miss some data. I'm sure that everything will be fine when the code in the skipped loop is run again. As I'm scraping a huge amount of data ( > 1 million sets of numbers ), I don't want to record the exceptional loops and ran them again manually. Is there any way to run the same loop again when catch an exception?

try{
    for(){
        someCode
        ...
    }
}catch(IOException){
}

Upvotes: 0

Views: 2119

Answers (5)

sp00m
sp00m

Reputation: 48837

I you want to redo the same loop iteration:

int i = 0;
int n = 15; // your n
for (i = 0; i < n; i++) {
    try {
        // some code
    } catch (Exception e) {
        i--;
    }
}

But be careful of an infinite looping! You should add a MAX_TRIES management.

Upvotes: 1

Mawia
Mawia

Reputation: 4310

This has a problem,

try{
    for(){
    //    someCode
        ...
    }
}catch(IOException){
  // Once exception happens your for() loop breaks !!!!!
}

Instead, do this...

 for () {

      try {
        // somecode
        // ..
      } catch ( IOException ioException ) {
        // handle(do something) here, not throwing error which will break the loop
      }

    }

Upvotes: 1

Jayamohan
Jayamohan

Reputation: 12924

You must be doing this. Do try catch inside the loop.

for(){
    try { 
            someCode
            ...
    } catch(IOException){
    }
}

Upvotes: 1

RNJ
RNJ

Reputation: 15552

Why not put the exception handling inside the loop

for(){
     try{
         // someCode
     }catch(IOException e){
        //handle exception if necessary
     }
}

Upvotes: 3

Matteo
Matteo

Reputation: 14930

Just put the try-catch inside the loop

for () {

  try {
    // somecode
    // ..
  } catch ( IOException ioException ) {
    // handle
  }

}

Upvotes: 5

Related Questions