JavaScript Error Handling

Handling and Managing Errors in JavaScript

JavaScript Error Handling

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.

Try...Catch Statement

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);
}

Throwing Custom Errors

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);
}

Finally Block

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");
}

Error Types

JavaScript has several built-in error types:

  • Error: Generic error
  • SyntaxError: Syntax error in code
  • ReferenceError: Reference to an undefined variable
  • TypeError: Operation on an inappropriate type
  • RangeError: Number outside of valid range

Async Error Handling

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");
}
}