Beginner Fundamentals

Error Handling

Errors are a normal part of programming. Handling them well keeps your program from crashing and gives users clear messages.

try and catch

Wrap risky code in a try block and handle problems in catch:

try {
  const data = JSON.parse("not valid json");
  console.log(data);
} catch (err) {
  console.error("Parsing failed:", err.message);
}

Throwing errors

Use throw to signal that something went wrong:

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

try {
  divide(10, 0);
} catch (err) {
  console.error(err.message); // Cannot divide by zero
}

Errors in async code

With async/await, use try/catch around await:

async function load() {
  try {
    const res = await fetch("https://example.com/data");
    const json = await res.json();
    console.log(json);
  } catch (err) {
    console.error("Request failed:", err.message);
  }
}

For plain Promises, use .catch.

Summary

Catch errors where you can recover, throw clear messages when something is wrong, and always handle async failures so they do not crash your app.