34. ASYNC | Error Handling in JavaScript
This article will talk about error handling in javascript.
The try...catch syntax allows us to catch errors so that the script instead of dying can do something more reasonable.
try {
// try the code
} catch (err) {
// handle the error
}
err variable contains the error object.It works like this:
First, the code in
tryis executed.If there is no error,
catchis ignored elsecatchis executed.
The error object
For all the built-in errors, the error object has three main properties viz. 1) name, 2) message and 3) stack.
try {
// try the code
} catch (err) {
console.log(err.name);
console.log(err.message);
console.log(err.stack);
}
Throwing Custom Error
- We can throw our own error by using the
throwsyntax.
if (age>100) {
throw new Error("Age can't be greater than 100.")
}
- We can also throw a particular error message by using the built-in constructor for standard errors.
throw new SyntaxError(message)
// OR
throw new ReferenceError(message)
finally block
It runs in all cases:
after
tryif there are no errors.after
catchif there are errors.
try {
// try the code
} catch (err) {
// handle the error
} finally {
// runs in all cases
}
If a finally block has a return, it overrides any return from the try (or catch) block.
function test() {
try {
return "from try";
} finally {
return "from finally";
}
}
console.log(test());
// Output: "from finally"
If finally has no return → original return is preserved.
function test() {
try {
return "from try";
} finally {
console.log("finally runs");
}
}
console.log(test());
/* Output:
finally runs
from try
*/
Using return inside finally is generally discouraged because:
It hides errors.
It overrides expected return values.
Makes debugging difficult.
try...catch works synchronously
If an error happens in scheduled code like Timers, etc., then try...catch won't catch it.
try {
setTimeout(() => {
// some error ocurred
}, 2000)
} catch (err) {
// handle the error
}
This is because the scheduled code is executed later when the JS engine has already left the try...catch construct.
Happy learning!

