Error handling in JavaScript lets your programs respond gracefully to unexpected situations instead of crashing. The main building blocks are try, catch, and finally, which work together to detect errors, handle them safely, and perform cleanup tasks.
try – Wraps code that might throw an error during execution.catch – Runs only if an error occurs inside the try block and receives an error object.finally – Always runs after try/catch, whether an error happened or not.name, message, and often stack for debugging.ReferenceError, TypeError, and SyntaxError.throw and new Error().A complete error-handling structure usually looks like this:
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that always runs (optional)
}
The JavaScript engine executes the try block first. If everything works, it skips directly to finally (if present). If an error is thrown inside try, control jumps to catch, then finally to finally.
Here, we just run a risky operation. If it throws an error, it will stop the script unless handled somewhere else.
try {
let result = riskyOperation();
console.log(result);
}
Now we add catch to safely handle any error that occurs in the try block.
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
}
The finally block runs after try/catch regardless of success or failure.
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("This runs no matter what");
}
You can validate input and throw a custom error when something is wrong.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
const result = divide(10, 0);
console.log("Result:", result);
} catch (error) {
console.error("Division failed:", error.message);
} finally {
console.log("Division attempt finished");
}
Enter a value. The script will try to convert it to a number. If it is not a valid number, a custom error is thrown and handled in catch.
finally.try to keep error handling precise.catch instead of leaving it empty — at least log something meaningful.finally for cleanup logic that must always run, such as closing connections or clearing intervals.error.message (and error.stack in development) to make debugging easier.finally; it should mainly be used for cleanup.try-catch block.finally to log "Operation completed" regardless of success or error.throw new Error("Custom message") and observe how catch receives it.