Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using continue statement within catch block in NodeJS

Tags:

node.js

Can we use continue and break statements within try and catch blocks

eg.,

for(let i=0; i< arr.length; i++) {
  try {
     // Some condition
     continue; 
  }
  catch(e) {
    continue;
  }
}
like image 947
Mahesh Siva S T Avatar asked Jul 11 '17 10:07

Mahesh Siva S T


1 Answers

The answer is: Yes.

Example:

for (let i = 0; i < 10; i++) {
  console.log(`Iteration ${i} start`);
  try {
    console.log(`Iteration ${i} try block`);
    if (i === 1) {
      throw new Error('error');
    } else if (i === 2) {
      continue;
    } else if (i === 3) {
      break;
    }
  } catch (e) {
    console.log(`Iteration ${i} catch block`);
    continue;
  }
  console.log(`Iteration ${i} end`);
}

This prints:

Iteration 0 start
Iteration 0 try block
Iteration 0 end
Iteration 1 start
Iteration 1 try block
Iteration 1 catch block
Iteration 2 start
Iteration 2 try block
Iteration 3 start
Iteration 3 try block

An even better example:

for (let i = 0; i < 10; i++) {
  console.log(`Iteration ${i} start`);
  try {
    console.log(`Iteration ${i} try block start`);
    if (i === 1) {
      throw new Error('error');
    } else if (i === 2) {
      throw new Error('continue');
    } else if (i === 3) {
      throw new Error('break');
    }
    console.log(`Iteration ${i} try block end`);
  } catch (e) {
    console.log(`Iteration ${i} catch block`);
    if (e.message === 'break') {
      console.log(`Iteration ${i} catch block: break`);
      break;
    } else if (e.message === 'continue') {
      console.log(`Iteration ${i} catch block: continue`);
      continue;
    }
    console.log(`Iteration ${i} catch block end`);
  }
  console.log(`Iteration ${i} end`);
}

Output:

Iteration 0 start
Iteration 0 try block start
Iteration 0 try block end
Iteration 0 end
Iteration 1 start
Iteration 1 try block start
Iteration 1 catch block
Iteration 1 catch block end
Iteration 1 end
Iteration 2 start
Iteration 2 try block start
Iteration 2 catch block
Iteration 2 catch block: continue
Iteration 3 start
Iteration 3 try block start
Iteration 3 catch block
Iteration 3 catch block: break

As you can see it all works as expected for both break and continue inside of try and catch blocks alike.

like image 105
rsp Avatar answered Oct 11 '22 13:10

rsp