2xshot
2xshot

Reputation: 11

Javascript for loop until error

I want to create a loop that will continue until it reaches an error then continues on...

for (var m = 0; m != 'Error'; m++)

If I push the iterations too high, it will throw a "TypeError", which indicates that the limit has been reached. This for loop exists inside another loop which needs to continue and not crash the script, just discontinue the loop.

Thanks!

EDIT CODE FOLLOWS:

for (var i = 0; i < 100; i++) {
  var xml = fs.readFileSync('./Filename-' + (i + 100) + '.xml', 'utf-8');
  var level1 = bb(xml)
  for (var m = 0;; m++) {
    try {
     if (level1.data.level2[m].product.code == '7472558') {
        console.log(level1.data.level2[m].product.code);
        total++}
    }
    catch (e) {
     break;
    }
  }
console.log(total)
}

Upvotes: 1

Views: 12443

Answers (2)

andyk
andyk

Reputation: 1688

You can wrap the code that throws the error in a try and then break in the catch block:

for (var m = 0;; m++) {
  try {
    // code that throws the error
  } catch (e) {
    // exit the loop
    break; 
  }
}

(Note that the loop above will only terminate if the code throws an error.)

Upvotes: 5

Dai
Dai

Reputation: 155145

while( someOuterLoopCondition ) {

    var m = 0;
    var innerLoopOK = true;
    while( innerLoopOK ) {

        try {

            // your original inner-loop body goes here

        } catch e {
            innerLoopOK = false;
        }

        m++;
    }
}

Or:

while( someOuterLoopCondition ) {
    for( var m = 0; m < upperBound; m++ ) {
        try {
            // your original inner-loop body goes here
        } catch e {
            break; // breaks inner-loop only
        }
    }
}

Upvotes: 0

Related Questions