By running the following, you can run code if an error is thrown.
try {
// test
} catch (e) {
// error output
}
Is there a similar way to run code only if no error is thrown?
By running the following, you can run code if an error is thrown.
try {
// test
} catch (e) {
// error output
}
Is there a similar way to run code only if no error is thrown?
Share Improve this question edited Jul 4, 2016 at 9:36 Warren Sergent 2,5974 gold badges37 silver badges44 bronze badges asked Jul 4, 2016 at 8:25 HimmatorsHimmators 15.1k39 gold badges136 silver badges233 bronze badges 2-
You can set a flag in the
catch
and then check it after. – alex Commented Jul 4, 2016 at 8:26 - I would remend checking the docs at developer.mozilla/en-US/docs/Web/JavaScript/Reference/… to get an understanding on how the try/catch/finally clauses works. – Jite Commented Jul 4, 2016 at 8:28
2 Answers
Reset to default 13Sure there is, see the ment inline.
try {
// test
// No error is thrown if program control reaches here
} catch {
// error output
}
Consider using an additional try
block in the "No error is thrown" part if you don't want the outer catch
to handle any other errors.
The accepted answer assumes that there is no return statements in the try block, which wasn't my case. In my case, there was multiple early return statements, and I wanted to run code as long as there wasn't an error. In that case you have a few options:
Using finally and a boolean to see if you got an error:
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');
}
}
}
This is pretty straightforward, preserves your return value and allows you do more plex error handling in the catch, so you could conditional set allGood whether you could recover from the error or not.
If your catch instead rethrows the error, you could use an immediately invoked function:
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;
}
Errors will bubble out and not run the console.log at the bottom. It bees even more succinct if you don't need a return value or catch:
function check () {
(() => {
if (condition1()) {
return;
}
if (condition2()) {
return;
}
doit();
})();
console.log('All good. No errors.');
}
Depending on what your function is throwing or returning, single or early returning, and how you want to handle the good/bad state, there's quite a few ways to handle it. You just have to pick what fits your code the best.