Errors: try, catch & throw

Errors: try, catch & throw in JavaScript: Things go wrong: a network drops, a file is missing, a user types letters into a number box.

Concept Explanation

Things go wrong: a network drops, a file is missing, a user types letters into a number box. Error handling is how you catch those failures gracefully instead of letting the whole app crash to a white screen.

JavaScript's tool is the try...catch block. You try risky code; if it throws, control jumps to catch, where you decide what to do. You can also throw your own errors to signal "this should never happen."


Syntax or Core Structure

try / catch / finally

function getConfig(json) {
  try {
    return JSON.parse(json);        // may throw if json is malformed
  } catch (err) {
    console.error("Bad config:", err.message);
    return {};                      // safe fallback
  } finally {
    console.log("Parse attempt finished"); // runs no matter what
  }
}

Throwing your own errors

function withdraw(amount, balance) {
  if (amount > balance) {
    throw new Error("Insufficient funds");
  }
  return balance - amount;
}

Real World Example

A checkout button wraps its payment call in try...catch. If the card is declined, the catch shows a friendly "Payment failed — try another card" message instead of a frozen page. The finally block re-enables the button either way, so the user is never left stuck.


Common Mistakes

  1. Swallowing errors: an empty catch (e) {} hides the problem. Always log or handle it.
  2. try/catch with async: a plain try/catch won't catch a rejected promise unless you await inside the try. For .then() chains, use .catch().
  3. Throwing strings: throw "oops" loses the stack trace. Throw a real Error: throw new Error("oops").

Best Practices

  • Catch what you can handle: don't wrap everything — only code where you can actually recover or report usefully.
  • Fail loudly in dev: log err.message and err.stack so bugs are visible, not silent.
  • Custom error types: class ValidationError extends Error {} lets callers tell which kind of failure happened.
  • Always await in the try: for async code, await the promise inside the try so rejections are actually caught.

Practice Exercises

  1. The Safe Parser: Write a function that JSON.parses a string and returns null (not a crash) on bad input.
  2. The Validator: throw new Error(...) when an age argument is negative, and catch it in the caller.
  3. The Finally: Add a finally block that logs "done" whether or not the try block succeeded.