Errors in JavaScript are unexpected issues that occur during code execution. They can be caused by syntax mistakes, undefined variables, or logical errors in your program.
eval()
function (rarely used).encodeURI()
or decodeURI()
.You can handle errors gracefully using the try...catch
block:
try {
let x = y + 1; // y is not defined
} catch (error) {
console.log("Error caught:", error.message);
}
Note: try...catch
only catches runtime errors, not syntax errors.
The finally
block always runs whether an error occurred or not.
try {
let num = 5;
num.toUpperCase(); // TypeError
} catch (error) {
console.log("Caught:", error.message);
} finally {
console.log("Finally block always runs.");
}
You can throw custom errors using the throw
statement:
function checkAge(age) {
if (age < 18) {
throw new Error("You must be 18 or older.");
}
return "Access granted.";
}
try {
checkAge(15);
} catch (e) {
console.log(e.message);
}
try...catch
to prevent crashing the entire app due to one unexpected error.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!