JavaScript Error Handling with try-catch

Sometimes, things go wrong in JavaScript — like when you try to use a variable that doesn't exist. This causes an error and can stop your whole script.

try...catch lets you handle those errors without crashing your program.

 What is try...catch?

It’s a way to "try" some code and "catch" any errors that happen.

try {
  // Code that might cause an error
} catch (error) {
  // Code to run if there is an error
}

 Simple Example

try {
  let x = y + 1; // 'y' is not defined
} catch (error) {
  console.log("Something went wrong!");
  console.log(error.message);
}

Even though y is not defined, the script won’t stop — it shows a friendly message instead.

 How it Works

  • try: Runs the code. If there's an error, it jumps to catch.
  • catch: Runs only if there was an error in try. It gives you an error object with details.
Tip: Use error.message to get a readable error description.

Real-life Example

function divide(a, b) {
  try {
    if (b === 0) {
      throw new Error("Cannot divide by zero!");
    }
    console.log(a / b);
  } catch (err) {
    console.log("Error: " + err.message);
  }
}

divide(10, 2); // Output: 5
divide(10, 0); // Output: Error: Cannot divide by zero!

Optional: finally Block

finally runs no matter what — after try and catch.

try {
  console.log("Trying something...");
} catch (e) {
  console.log("Error!");
} finally {
  console.log("This always runs!");
}

 Common Mistakes

  • Don’t use try...catch to handle things you can check for, like empty input.
  • try...catch only works for runtime errors, not syntax errors (like missing brackets).

 Final Takeaways

  • try...catch helps your code keep running even if something goes wrong.
  • Use it around code that might break — like API calls or risky calculations.
  • catch gives you details about what went wrong.
  • finally runs no matter what — great for clean-up code.
 Best Practice: Catch errors and show friendly messages — don’t just crash your app!