Skip to main content
JavaScript & the browser·Module C7 · Lesson 1
TaskWrite parseAge(s) that throws Error('not a number: <s>') if Number(s) is NaN, else returns the number. Call it once with '25' and log the result. Wrap a call with 'forty' in try/catch and log 'caught: ' + err.message.

throw and catch — the basic shape

75 XP6 min
Theory

throw stops execution

throw expression aborts the current function and walks up the call stack until a catch block grabs it. Anything is throwable, but you should throw Error objects — they carry a stack trace.

function parseAge(s) {
  const n = Number(s);
  if (Number.isNaN(n)) throw new Error("not a number: " + s);
  if (n < 0)           throw new Error("age cannot be negative: " + n);
  return n;
}

try {
  parseAge("forty");
} catch (err) {
  console.log("caught:", err.message); // caught: not a number: forty
}

The contract

  • try — code that might throw.
  • catch (err) — runs only if try threw. err is whatever was thrown.
  • The catch parameter can be untyped (catch (err)) — TypeScript-aware editors treat it as unknown until you narrow.

Don't throw strings

throw "broken" works syntactically but loses the stack trace and breaks tooling. Always throw new Error("broken").

🔒

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial — card required, cancel anytime.

Sign up — free trial →

First 10 lessons in each track are free. No card needed for those.

PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.