Lesson: Error Handling with try, throw, and catch

Objective

Understand how JavaScript handles errors using try, throw, and catch, and why this is important when writing reliable programs.


Why Error Handling Matters

When code runs, things can go wrong:

  • A user enters the wrong input.
  • Data from an API is missing or corrupted.
  • A calculation doesn’t make sense (like dividing by 0).

Without error handling, the program might crash completely.
With error handling, we can catch problems and respond safely.

1. try

  • The “test zone.”
  • Put code here that might cause an error.
  • If everything works, the program continues normally.
  • If something fails, it jumps straight to the catch.


try {
  let x = JSON.parse("oops"); // invalid JSON
} catch (err) {
  console.log("Error caught:", err.message);
}

2. throw

  • The “signal flare.”
  • Lets you create your own errors on purpose.
  • Use when you detect something wrong in the data.
try {
  let age = -3;
  if (age < 0) {
    throw "Age cannot be negative!";
  }
} catch (err) {
  console.log("Error caught:", err);
}

3. catch

  • The “safety net.”
  • Runs only if an error happened in the try.
  • Gives you a chance to explain or fix the issue instead of crashing.
try {
  throw "Something went wrong!";
} catch (error) {
  console.log("Error caught:", error);
}

All Together

try {
  let userInput = "not-a-number";
  let number = Number(userInput);

  if (isNaN(number)) {
    throw "Invalid number input!";
  }

  console.log("Valid number:", number);
} catch (err) {
  console.log("Oops, error:", err);
}

✅ Summary

  • try → test code that might fail.
  • throw → create or signal an error.
  • catch → handle the error safely.

This keeps programs from crashing and helps you control what happens when something goes wrong.