Error Handling in JavaScript

๐Ÿ“˜ What is Error Handling?

Error handling is the process of responding to and managing exceptions (errors) that occur during the execution of code, allowing programs to recover gracefully instead of crashing.

โš ๏ธ Why Do Errors Occur?

โœ… How to Handle Errors in JS?

try {
  let data = JSON.parse("{ invalid json }");
} catch (error) {
  console.error("Caught an error:", error.message);
} finally {
  console.log("This always runs.");
}

๐Ÿ” Try, Catch, Finally Explained

๐Ÿงจ Throwing Errors Manually

function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero!");
  return a / b;
}

๐Ÿงฑ JavaScript Error Object

โš™๏ธ Common Error Types

โณ Async & Await async/await

Know more in Detail
async function fetchUser() {
  try {
    let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
    let user = await res.json();
    console.log(user);
  } catch (err) {
    console.error("Failed to load user:", err.message);
  }
}

๐Ÿงช Live Demo: Error Catching in Action

๐Ÿ“š Practice Questions

โ“ FAQ

What happens if an error is not caught?

The script will stop running and a message will be shown in the browser console.

Can you use try-catch with async functions?

Yes, wrap the await calls in a try-catch block to handle asynchronous errors.

Should I always use try-catch?

Use it when you expect possible runtime errors and want to prevent app crashes.

What is the difference between try-catch and .catch() on promises?

try-catch works with async/await, while .catch() is used with promise chains.

๐Ÿง  Final Summary