Handling and Managing Errors in JavaScript
Error handling in JavaScript is crucial for managing unexpected situations and preventing your application from crashing. It allows you to gracefully handle errors and provide meaningful feedback to users or developers.
The try...catch statement is used to handle exceptions that might be thrown in a block of code.
try {
// Code that may throw an error
let result = someUndefinedVariable + 10;
} catch (error) {
console.log("An error occurred:", error.message);
}
You can throw custom errors using the throw statement.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.log("Error:", error.message);
}
The finally block is executed regardless of whether an exception was thrown or caught.
try {
// Some code that might throw an error
} catch (error) {
console.log("An error occurred:", error.message);
} finally {
console.log("This will always execute");
}
JavaScript has several built-in error types:
Error: Generic errorSyntaxError: Syntax error in codeReferenceError: Reference to an undefined variableTypeError: Operation on an inappropriate typeRangeError: Number outside of valid range
For asynchronous code, you can use try...catch with async/await or handle errors in Promise chains.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Failed to fetch data:", error);
} finally {
console.log("Fetch operation completed");
}
}