typescript · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Something throws halfway. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
try {
console.log("Packing");
throw new Error("Out of boxes");
console.log("Posting");
} catch (err) {
if (err instanceof Error) console.log(err.message);
}
console.log("Shop closed");
your turn
Your turn. Refuse an impossible booking.
Fill in the word that raises an error, a booking bigger than the 10 free seats, and the property that holds the error's text.
fix it
The checker does not trust the error. Fix it!
- Read the error:
TS18046: 'err' is of type 'unknown'.Anything can be thrown, so the checker is careful. - Narrow
errfirst. Only anErroris sure to have a message. - Put
if (err instanceof Error)in front ofconsole.logon line 8, then press run.
nailed it
you can catch trouble before it crashes. :D
throw new Error("...")raises an error on purpose.tryruns risky code, andcatchdeals with any error.- Check
err instanceof Errorbefore readingerr.message.
new words in your collection
- throw
- try
- catch
- instanceof
This lesson isn’t saved. A free account remembers every lesson you finish.