gpt4 book ai didi

javascript - 在 NodeJS 的 catch block 中使用 continue 语句

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:08 25 4
gpt4 key购买 nike

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

例如,

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

最佳答案

答案是:是的。

示例:

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

正如您所看到的,对于 trycatch 内部的 breakcontinue 来说,一切都按预期工作。 block 相似。

关于javascript - 在 NodeJS 的 catch block 中使用 continue 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45032624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com