×

typescript · level 2 · unit 7 · lesson 2

  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 an error on purpose, and deals with it.

Some problems are not typos. A server is down, or an order is for zero pies. You can throw an error on purpose with throw new Error("Order at least one pie"). It stops the function right there, like the errors you have seen.

Wrap risky code in and add catch (err) { } after it. If anything inside try throws, the program jumps to catch instead of crashing. If nothing throws, catch is skipped.

Anything can be thrown, so err is unknown. Check it with , which asks whether it was made by new Error. Then read err.message.

function order(quantity: number): string {
  if (quantity < 1) throw new Error("Order at least one pie");
  return `${quantity} pies ordered`;
}
try {
  console.log(order(2));
  console.log(order(0));
} catch (err) {
  if (err instanceof Error) console.log(`Sorry: ${err.message}`);
}

When an if guards one short line, you may leave out the curly brackets, as on lines 2 and 9.