在NodeJS

时间:2017-07-11 10:58:50

标签: node.js

我们可以在try和catch块中使用continue和break语句

例如,

for(let i=0; i< arr.length; i++) {
  try {
     // Some condition
     continue; 
  }
  catch(e) {
    continue;
  }
}

1 个答案:

答案 0 :(得分:1)

答案是:是的。

示例:

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`);
}

打印:

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

更好的例子:

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`);
}

输出:

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

正如您所看到的那样,对于breakcontinue块内的trycatch都可以正常工作。