如果抛出错误,您可以通过运行以下代码来运行代码。
try {
// test
} catch (e) {
// error output
}
如果没有错误抛出,是否有类似的方法只运行代码?
如果抛出错误,您可以通过运行以下代码来运行代码。
try {
// test
} catch (e) {
// error output
}
如果没有错误抛出,是否有类似的方法只运行代码?
当然有,看一下内联评论即可。
try {
// test
// No error is thrown if program control reaches here
} catch {
// error output
}
如果您不希望外层的catch
处理任何其他错误,请考虑在"没有错误被抛出"部分使用额外的try
块。
function check () {
let allGood = true;
try {
if (condition1()) {
return 'foo';
}
if (condition2()) {
return 'bar';
}
return doit();
} catch (e) {
allGood = false;
console.error('Oh no!', e);
return 'bad';
} finally {
if (allGood) {
console.log('All good');
}
}
}
这非常简单,保留了您的返回值,并允许您在catch中进行更复杂的错误处理,因此无论您能否从错误中恢复,都可以有条件地设置allGood。
如果您的catch重新抛出错误,您可以使用一个立即调用的函数:
function check () {
const result = (() => {
try {
if (condition1()) {
return 'foo';
}
if (condition2()) {
return 'bar';
}
return doit();
} catch (e) {
console.error('Oh no!', e);
throw e;
}
})();
console.log('All good. Also I have access to', result);
return result;
}
错误将被传递并且不会运行底部的console.log。如果您不需要返回值或捕获,它将变得更加简洁:
function check () {
(() => {
if (condition1()) {
return;
}
if (condition2()) {
return;
}
doit();
})();
console.log('All good. No errors.');
}
catch
中设置一个标志,然后在之后进行检查。 - alex