← Back to JavaScript Course | Chapter 8: Error Handling | Lesson 1 of 6

JS Error Handling

What Is Error Handling

Error handling means anticipating that some operations can fail and writing code that responds gracefully instead of letting the whole program crash with an uncaught exception. A try/catch block is the primary tool for this, letting risky code run while still having a defined fallback path if it fails.

Example: What Is Error Handling

javascript
try {
  JSON.parse("not valid json");
} catch (error) {
  console.log("Handled gracefully:", error.message);
}

Throwing Errors

You raise a problem with throw, which immediately stops normal execution and looks for the nearest enclosing catch block able to handle it, unwinding the call stack as needed. You can throw any value in JavaScript, but throwing an Error object (or a subclass of it) is standard practice since it captures a useful stack trace.

Example: Throwing Errors

javascript
function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Insufficient funds");
  }
  return balance - amount;
}
try {
  withdraw(100, 200);
} catch (e) {
  console.log(e.message);
}

Handling Different Situations

Different failures need different responses — a missing network connection might warrant a retry, while invalid user input should show a message rather than silently failing. Treating every error identically, with one generic catch-all message, often hides useful information that could help the user or the developer.

Example: Handling Different Situations

javascript
function processInput(value) {
  if (typeof value !== "number") {
    console.log("Invalid input, please enter a number");
  } else {
    console.log("Processing:", value);
  }
}
processInput("abc");

Good Error Handling

Good error handling reports enough detail to diagnose the problem, via error.message or a custom error type, without leaking sensitive internals like stack traces or database details to the end user.

Example: Good Error Handling

javascript
try {
  throw new Error("Database connection failed");
} catch (error) {
  console.log("Error occurred:", error.message); // useful detail, no internals leaked
}

Error Handling Best Practices

As a rule of thumb, catch errors close to where you can actually do something useful about them, and let errors you can't handle propagate up to a boundary that can. Logging errors with enough context (what operation failed, with what input) makes debugging production issues dramatically easier later.

Example: Error Handling Best Practices

javascript
function riskyOperation() {
  throw new Error("Something failed");
}
try {
  riskyOperation();
} catch (e) {
  console.log("Handled where we can act:", e.message);
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.