Make a function refuse a value it cannot work with by throwing an error instead of giving back a fake answer, and catch that error with try and catch so the program carries on. Read the error’s message once you have checked that it is one.
Fundamentals
TypeScript
`throw` and `try` / `catch`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
The RangeError that stopped bar.ts in the last lesson did not
come from your code. It came from repeat. Handed −2, it had no
text to give back, so it refused, and Node stopped on its line.
Sooner or later every function meets a value like that: one it
cannot work with, while its type promises an answer.
A cook who opens the fridge for an omelette and finds no eggs does not
send out an empty plate, and does not walk into the dining room to
explain. The order goes back to the waiter, who can talk to the guest
and offer pancakes instead. In this lesson your functions refuse a bad
value the way repeat did, and the part of the program that called
them catches the refusal and carries on.
A function that cannot do its job
In the last lesson the if that checked done stood in the main
code, around the lines that drew the bar. Put the bar in a function,
so any part of a program can draw one, and the check moves inside
it. bar promises a string, the bar. With 7 done out of 5 there is
no bar to give back, and the easy way out is to give back the
message instead:
Bad — the message comes back as if
it were a bar, and is printed as one.
bar.tsts
function bar(done: number, total: number): string { if (done < 0 || done > total) { return `Done must be 0 to ${total}`; } return "#".repeat(done) + "-".repeat(total - done);}const done = 7;console.log(`[${bar(done, 5)}] ${done} of 5 done`);
Good — bar refuses, and nothing
pretends to be a bar.
bar.tsts
function bar(done: number, total: number): string { if (done < 0 || done > total) { throw new Error(`Done must be 0 to ${total}`); } return "#".repeat(done) + "-".repeat(total - done);}const done = 7;console.log(`[${bar(done, 5)}] ${done} of 5 done`);
Run both. The first prints [Done must be 0 to 5] 7 of 5 done: a
sentence in the brackets where the bar should be, and as far as the
program knows, nothing went wrong. Every line that calls bar would
have to remember to look at what came back. The second prints only
Error: Done must be 0 to 5: bar refused, the way repeat did,
and the last line never ran.
throw ends the function on its line and gives nothing back: no
return runs, and the line that called it never gets an answer. What
it throws is usually an error, a value that says what went wrong.
new Error("…") makes one, the way new Map<string, number>() made
an empty Map in lesson 6.10, and the text you give it becomes its
message. JavaScript's own errors are made the same way: the
RangeError from repeat is one, and its message is Invalid count value: -2.
When nothing catches an error, the program stops there, as it stopped
for repeat, and every line after it is skipped. In your terminal
Node prints more than the page: the file and line that threw, that
line with a ^ under it, the Error: line, the stack trace of lesson
5.8, and, last of all, Node's version (lesson 1.5). That is the right
end for a bug. For a bad value the person typed, it is not: they get a
stack trace instead of a sentence.
Catching it: try and catch
try marks the lines that may throw, and catch the block
that runs instead if one of them does:
If nothing in the try throws, the catch block is skipped. If
something throws, even deep inside a function the try called, every
line still waiting to run is skipped, up to the catch: the rest of
that function, the rest of every function waiting for its answer, and
the rest of the try. The error lands in the box named between the
parentheses, here error, and after the catch the program goes on
with the next line, or with the loop's next turn when the try is
inside a loop. The catch is the waiter: the refusal comes back to
it, and it decides what happens next.
A second function, progress, builds the whole line around the bar,
[##---] 2 of 5 done, as bar.ts printed it in the last lesson, and
a try calls it. Follow one call of progress, with a good count and
with a bad one: switch between the two runs, press Next step to
walk through one, or let it play.
Now the whole file, with both calls in one try. Press Step to
walk through it line by line, and watch the Call stack column from
line 13 on: progress and bar each get a card, and when line 3
throws, the next step is line 16:
Every bar drawn never prints: both cards left the pile at once, and
neither gave back an answer.
What catch receives
A bar could not be drawn is true, but vague. The error already says
what went wrong, in its message, so print that instead. A first
version has a type error:
The type error is on line 10: 'error' is of type 'unknown'. The
reason is that throw takes any value, not only an error: throw "no eggs" throws a string, throw 7 a number. So in a catch,
TypeScript cannot know what landed in error, and gives it the type
unknown: a value that could be of any type, which TypeScript
lets you use only after you check what it is. Lesson any vs
unknown: the escape hatch and the safe box, two lessons on, is
about unknown; here you need only one check.
That check is instanceof, read as "is an instance of", meaning
"was made by". error instanceof Error is true when the value was
made by new Error, or is one of JavaScript's own errors, like
RangeError. It narrows, as typeof did in lesson 7.3: inside the
if, TypeScript knows error is an Error, so message is there:
It prints Done must be 0 to 5: the sentence bar wrote, printed by
the part of the program that decided to show it.
Predict which lines print
Read the program and follow the lines in order. Which ones reach the
output?
Predict
What is the third line it prints?
The common mistake: a box made in the try
A try block is a block like an if's, between braces. A box made
inside it lives only there.
Common mistake
Using a box made inside a try after the try
parseDone turns typed text into a number and, with Number.isNaN
(is it NaN, not a number? lesson 2.5), refuses text that is not a
number. You call it inside a try, because it may throw, and print
the result after:
On line 13 there is no done. The one on line 9 was made inside the
try's braces and was gone when they closed, as a box made inside an
if is gone after it (lesson 3.1). The done on line 2 is
parseDone's own, gone when it returns (lesson 5.5).
Cannot find name 'done'.
The fix
Move the line that needs the box into the try, under the line that
makes it:
It prints Done: 2. The fix is also what you want: if parseDone
throws, there is no number, and the line that prints it should be
skipped with the rest of the try. The other way out, let done: number; above the try, does not help: TypeScript answers Variable 'done' is used before being assigned., because it knows the try may
have stopped before done = parseDone("2"); filled the box. When
TypeScript cannot find a box after a try, put the lines that use it
inside.
Pass all three tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What happens to the lines after a throw in its function?
Check yourself
When does a catch block run?
Check yourself
Why is a caught error of type unknown?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
throw and try / catch
What things are
Word
What it means
throw
Ends the function with an error instead of an answer
Error
A value that says what went wrong
message
The error's text, given to new Error
try block
Lines that may throw
catch block
Runs only when something in the try throws
unknown
The type of what a catch gets: check it first
Code
Write
To
throw new Error("…")
Refuse a value, and say why
try { … }
Run lines that may throw
catch (error) { … }
What to do instead, if one throws
error instanceof Error
Check that it is an error
error.message
Read its text, inside that check
Rules
Rule
What it means
Refuse, do not pretend
Throw instead of giving back a fake answer
A throw skips
Its function, every caller waiting, the rest of the try
Nobody catches
The program stops, as for JavaScript's own errors
After the catch
The program goes on with the next line
Boxes in a try
Live only inside its braces
Where to go next
You can now make a function refuse a value it cannot work with, catch
the refusal so the program carries on, and read the error's message
once you have checked that it is one.
Next is Where to throw and where to catch: friendly errors for bad
commands. TaskKit still prints a summary nobody asked for after a
command it does not know. That lesson puts the refusal where the
command is read and the catch where TaskKit talks to you, so a bad
command gets one line that says what to type instead.
Before you move on, give bar a second check of your own: refuse a
total of 0 or less with new Error("Total must be more than 0"),
above the check for done. In the last progress.ts, the one whose
catch prints error.message, change bar(7, 5) to bar(2, 0), and
predict first: with a total of 0, a done of 2 fails the done
check too, so which of the two messages does the catch print, and
why that one? Then move your check below the one for done, and run
it again.
try
progress
bar
catch
try: callscallscalls
progress: calls barcallsbarcallsbar
bar: returnsreturnsreturns
progress: returnsreturnsreturns
try: printsprintsprints
catch: skippedskippedskipped
Time
The try block calls progress(2).
progress calls bar(2, 5) and waits for its answer.
2 is between 0 and 5, so bar gives back "##---".
It builds its line around the bar and gives it back.
The line comes back, and the try prints it: [##---] 2 of 5 done.
Nothing was thrown, so the catch block never runs.
With 7, every line still waiting after the throw is
skipped, up to the catch
All 6 steps shown.Step 1 of 6: try: callsStep 2 of 6: progress: calls barStep 3 of 6: bar: returnsStep 4 of 6: progress: returnsStep 5 of 6: try: printsStep 6 of 6: catch: skipped
All 6 steps shown.
try
progress
bar
catch
try: callscallscalls
progress: calls barcallsbarcallsbar
bar: throwsthrowsthrows
progress: skippedskippedskipped
try: skippedskippedskipped
catch: printsprintsprints
Time
The try block calls progress(7).
progress calls bar(7, 5) and waits for its answer.
7 is more than 5: bar throws an Error and stops on line 3.
No answer ever comes, so the rest of progress is skipped.
The rest of the try is skipped: nothing is printed here.
The error lands here, and the catch prints its line.
With 7, every line still waiting after the throw is
skipped, up to the catch
All 6 steps shown.Step 1 of 6: try: callsStep 2 of 6: progress: calls barStep 3 of 6: bar: throwsStep 4 of 6: progress: skippedStep 5 of 6: try: skippedStep 6 of 6: catch: prints
All 6 steps shown.
Exercise · Read the code
Where the run goes on
addTask calls checkTitle, and the try calls addTask with a
title that is only spaces. Which lines does the program print?
ts
function checkTitle(title: string): string { if (title.trim() === "") { throw new Error("A task needs a title"); } return title.trim();}function addTask(title: string): string { const tidy = checkTitle(title); console.log("Checked"); return `Added: ${tidy}`;}try { console.log(addTask(" "));} catch (error) { console.log("Not added");}console.log("Bye");
ts
try { // Lines that may throw} catch (error) { // What to do instead}
progress.tsts
function bar(done: number, total: number): string { if (done < 0 || done > total) { throw new Error(`Done must be 0 to ${total}`); } return "#".repeat(done) + "-".repeat(total - done);}function progress(done: number): string { const line = `[${bar(done, 5)}] ${done} of 5 done`; return line;}try { console.log(progress(2)); console.log(progress(7)); console.log("Every bar drawn");} catch (error) { console.log("A bar could not be drawn");}console.log("Keep going");
progress.tsts
function bar(done: number, total: number): string { if (done < 0 || done > total) { throw new Error(`Done must be 0 to ${total}`); } return "#".repeat(done) + "-".repeat(total - done);}try { console.log(bar(7, 5));} catch (error) { console.log(error.message);}
progress.tsts
function bar(done: number, total: number): string { if (done < 0 || done > total) { throw new Error(`Done must be 0 to ${total}`); } return "#".repeat(done) + "-".repeat(total - done);}try { console.log(bar(7, 5));} catch (error) { if (error instanceof Error) { console.log(error.message); }}
ts
function left(planned: number, spent: number): number { if (spent > planned) { throw new Error("Over the plan"); } return planned - spent;}console.log("Start");try { console.log(left(30, 10)); console.log(left(30, 45)); console.log("All on plan");} catch (error) { console.log("Caught");}console.log("End");
done.tsts
function parseDone(typed: string): number { const done = Number(typed); if (Number.isNaN(done)) { throw new Error(`Not a number: ${typed}`); } return done;}try { const done = parseDone("2");} catch (error) { console.log("Done must be a number");}console.log(`Done: ${done}`);
done.tsts
function parseDone(typed: string): number { const done = Number(typed); if (Number.isNaN(done)) { throw new Error(`Not a number: ${typed}`); } return done;}try { const done = parseDone("2"); console.log(`Done: ${done}`);} catch (error) { console.log("Done must be a number");}
Exercise · Fix the error
Refuse instead of pretending
minutesEach shares the minutes you have among your tasks. With no
tasks it gives back −1, and the program prints
Each task: -1 minutes. Make it throw an error with the message
No tasks to share the time instead, and put the two
console.log lines in a try whose catch prints the error's
message. It should print Each task: 20 minutes, then the message.
Loading the editor…
Exercise · Write the code
Check every count, and keep going
counts holds four counts someone typed, out of 5 tasks, and
parseDone from the common mistake already refuses text that is not
a number. Make it also refuse a number outside 0 to 5, with the
message Done must be 0 to 5, not 7 (the typed text at the end).
Then, for every count, print Done: and the number, or the
error's message, so one bad count does not stop the rest.