JavaScript errors occur when the JavaScript engine cannot execute your code correctly. This may be due to syntax mistakes, invalid operations, or referencing variables that do not exist. When something goes wrong, JavaScript throws an error object and the current execution stops unless the error is handled.
Understanding error types and how to handle them using try...catch and finally is essential for building reliable applications.
throw keyword).try...catch to handle errors gracefully.Common built-in error types in JavaScript include:
eval() function.The basic syntax for handling errors in JavaScript is the try...catch structure:
try contains code that might fail. If an error occurs inside try, the control jumps to the catch block, where you can access the error object. An optional finally block always runs, whether an error occurred or not.
try...catch...finally Structure
try {
// Code that may throw an error
} catch (error) {
// Handle the error
} finally {
// Cleanup code (always runs)
}
JavaScript uses the Error object to represent problems. An Error object typically contains:
name: Type of error (example: ReferenceError).message: A human-readable explanation.
// Variable not declared
console.log(x);
try...catch
try {
// y is not defined
let result = y + 10;
} catch (error) {
console.log("Error caught: " + error.message);
}
finally Block
try {
let result = 10 / 2;
console.log("Result:", result);
} catch (e) {
console.log("Error:", e.message);
} finally {
console.log("Cleanup actions here");
}
let age = -5;
if (age < 0) {
throw new Error("Age cannot be negative");
}
Error Object
try {
throw new Error("Something went wrong");
} catch (err) {
console.log(err.name);
console.log(err.message);
}
console.log(x) → ReferenceError: x is not definedy + 10 inside try → Error caught: y is not definedfinally block runs even if an error occursUncaught Error: Age cannot be negativetry...catch.Error objects instead of plain strings.finally for cleanup logic.TypeError using null.toUpperCase().JSON.parse() inside try...catch.throw new Error().ReferenceError, TypeError, and RangeError.finally block.