×

javascript · level 3 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

raises the alarm; decides what happens next.

So far an error stopped your whole program. Professionals plan for errors. throw new Error("message") stops the current function on purpose and passes the error upwards, through every caller, until something catches it.

Wrap risky code in try...catch. If anything inside try throws, JavaScript jumps to catch (error), where error.name and error.message tell you what happened. A block runs afterwards either way, perfect for tidying up.

function parseAge(text) {
  const age = Number(text);
  if (Number.isNaN(age)) { throw new Error(`"${text}" is not a number`); }
  return age;
}
for (const input of ["42", "forty"]) {
  try {
    console.log(`Age ${parseAge(input)}`);
  } catch (error) {
    console.log(`${error.name}: ${error.message}`);
  } finally {
    console.log(`Checked ${input}`);
  }
}

Number("forty") gives NaN, short for Not a Number, and Number.isNaN spots it.