T4 JavaScript · Lesson 10
Errors and debugging
When something goes wrong: the error objects and their kinds, throwing errors of your own with a clear message, catching them with try, catch and finally, where to catch and where to let an error fly, checking input at the edges, and a method for finding any bug in a JavaScript program.
- read an error object's name and message, and tell the common kinds apart
- throw an error of your own, of the right kind, with a message that says what went wrong
- catch an error with try and catch, and run clean-up code with finally
- decide where to catch an error, and when to let it go on up
- check data where it enters a program, so that a bad value is caught early and named
- find a bug with the method of this path: read, reproduce, cut down, print and fix
The back cover
Every program meets things that go wrong: a missing file, a word where a number should be, a name spelt wrongly. JavaScript reports each fault as an error object, with a kind and a message. It sends the object up through the running functions until something deals with it.
These pages show the kinds of error and how to throw one of your own, with a message that names the bad value. They show try, catch and finally, and where to catch an error or let it fly. They show why data is checked at the gates. Last comes the method, used on a whole program with a bug that throws nothing.
Before you start
The story: One bad gear
On Saturday morning the harbour board went dark from top to bottom: not one ferry time, not one Remind me button, only black glass. The night before, someone had sent the board its timetable with one line damaged, a time written as 4..15.
Through the diary lens there is a single red line, about that one time, and nothing after it.
"One bad gear," says Master Hakim Verge, "and the whole clock stops. A good clock notices the bad gear, says plainly which one it is, and keeps the other hands turning." Corin suggests telling the harbour office never to make mistakes. Master Verge does not answer that.
Every program meets values it did not expect: a box left empty, a file that arrives damaged, a server that does not answer. In the Learning to learn step you learnt to read the red line an error leaves, and a method for finding the slip behind it. This lesson goes further. It shows how errors work inside JavaScript, and how to raise one of your own on purpose. It shows how to catch one, so that a single bad value does not stop everything, and where in a program each of those belongs.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| The three error kinds. | SyntaxError, ReferenceError, TypeError. | With RangeError, as objects you can catch. |
| Reading a trace. | at checkAge (line 3) | The trace of an error you throw yourself. |
| The debugging method. | Read, reproduce, cut down, print, fix. | Used on a whole program at the end. |
| Objects. | err.message | An error is an object with a name and a message. |
| Guard clauses. | if (age < 0) return "not a real age"; | Throwing instead of returning a string. |
| Functions calling functions. | The call stack. | An error travels back down it until caught. |
| Converting text. | Number("two") is NaN. | Checking input where it arrives. |
| JSON.parse. | JSON.parse("{bad") | It throws when the text is broken. |
| Silent slips. | NaN, undefined, a wrong answer. | Turning them into loud, early errors. |
| The Console and breakpoints. | The DevTools step. | Where you watch an error happen. |
By the end of this lesson you will be able to:
- read an error object's name and message, and tell the common kinds apart;
- throw an error of your own, of the right kind, with a message that says what went wrong;
- catch an error with
tryandcatch, and run clean-up code withfinally; - decide where to catch an error, and when to let it go on up;
- check data where it enters a program, so that a bad value is caught early and named;
- find a bug with the method of this path: read, reproduce, cut down, print and fix.
How to follow this lesson
Every block on this page runs. Some stop with a red line on purpose, to show what an uncaught error looks like. When you write your own, print err.name and err.message rather than the error itself, which each tool prints in its own way.
In one line
An error is an object that stops a program unless something catches it; you can raise one on purpose and catch it where you can do something useful.
Errors are objects
At a glance
When a train's signal fails, the driver does not get a vague feeling that something is wrong. A fault card drops: what failed, and where. JavaScript does the same.
When something goes wrong as a program runs, it makes an error object and throws it up through the running functions. The object has a name, the kind of fault, and a message that says what happened. TypeError, ReferenceError, RangeError and SyntaxError are the common kinds. A NaN, an undefined or an Infinity throws nothing: each is a value, not an error.
Take a guess: Does the same runaway recursion give the same kind of error in every browser?
When a train's signal fails, the driver does not get a vague feeling that something is wrong. A fault card drops: what failed, and where. JavaScript does the same. When something goes wrong while a program runs, it makes an object that describes the fault, and throws it: sends it back up through the functions that are running, looking for code that will deal with it.
An object made when something goes wrong, with a name that says the kind of error, such as TypeError, and a message that says what happened.
Until now, every error you met stopped the program, and the page printed it in red. That is what happens when nothing deals with it. The block below deals with one, with try and catch, which the catching section of this lesson explains fully. For now, look only at what the error object holds:
try {
const user = null;
console.log(user.name);
} catch (err) {
console.log(err.name, "|", err.message);
}
console.log("still running");
TypeError | Cannot read properties of null (reading 'name')
still running
The error's name is TypeError, and its message is the text you have seen in red so many times. And this time the program did not stop: the last line ran. The red line you know from the Learning to learn step is the page printing an error that nobody caught, as Uncaught, its name, its message and its trace.
The kinds you meet most
| Name | It means | A typical cause |
|---|---|---|
| SyntaxError | the code, or some text being read as code or JSON, cannot be read | a bracket that never closes; broken JSON |
| ReferenceError | a name that does not exist here | a misspelt name; a name used outside its scope |
| TypeError | a value of the wrong type for the job | reading a property of null; calling something that is not a function |
| RangeError | a number outside what is allowed | a function that never stops calling itself; a negative array length |
| Error | the general kind, for errors you throw yourself | a rule of your own program, broken |
Every kind is a special case of Error, so err instanceof Error is true for all of them, and err instanceof TypeError is true only for a TypeError. Read instanceof aloud as "is a kind of":
try {
null.x;
} catch (err) {
console.log(err instanceof TypeError, err instanceof Error, err.constructor.name);
}
true true TypeError
A SyntaxError while the program runs
A SyntaxError in your own code stops the program before it starts, as the values lesson showed. But text read while the program runs can be broken too. JSON.parse reads text, and throws a SyntaxError when the text is not valid JSON. Unlike a slip in the code, this one can be caught, because the program is already running:
try {
JSON.parse("{bad");
} catch (err) {
console.log(err.name);
console.log(err.message);
}
SyntaxError
Expected property name or '}' in JSON at position 1 (line 1 column 2)
What does not throw
Many wrong answers are not errors at all, as earlier lessons showed. Dividing by zero gives Infinity, failed arithmetic gives NaN, a missing property gives undefined. None of them throws, so no catch will ever see them:
try {
console.log(10 / 0, Number("abc") + 1, ({}).price);
} catch {
console.log("caught");
}
Infinity NaN undefined
These quiet values are often worse than an error, because the program carries on with them, and the wrong answer turns up far from its cause. The checking section shows how to turn them into loud, early errors.
Every error message has a page on MDN, in its JavaScript error reference, with the cause and the usual fixes. Searching for the message's words, as the Learning to learn step taught, usually finds it at the top.
Worked example 1
A results portal's script reads a student record and prints the total. Sometimes the record is missing, and the script stops. Catch the error to see its name and message, and say what kind it is and why.
What we have: a record that is sometimes null
What we need: the error's kind and message, and its cause
The plan: wrap the reading in try, and print err.name and err.message in catch
const record = null;
try {
console.log(record.marks.total);
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
TypeError: Cannot read properties of null (reading 'marks')
- The kind is TypeError, as null is a value of the wrong type for reading a property. The message names the property, marks, which shows how far the script got.
A TypeError: the record was null, and the script tried to read its marks.
Check: the message says reading 'marks', the first property read from the record.
A path that fails: guessing that marks is spelt wrongly and renaming it. The message says the record itself is null; a spelling slip would give undefined for marks and fail one step later, at total.
When you are stuck: an error's meaning is not clear
Read its name first: it tells you the kind of slip before you read a word of the message.
Then read the message, slowly, and look for the name or property it quotes.
Search MDN's error reference for the message, without your own names in it.
Remember that NaN, undefined and Infinity are not errors: no catch will see them.
Your turn
try {
undefinedName + 1;
} catch (err) {
console.log(err.name);
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
ReferenceError
- undefinedName was never made.
- Using a name that does not exist is a ReferenceError.
It prints ReferenceError.
Is err instanceof Error true for a TypeError?Tap to reveal
- Every kind of error is a special case of Error.
- So a TypeError is also an Error.
Yes.
Why can a catch never see the NaN of Number("two") * 3?Tap to reveal
- Failed arithmetic gives NaN; it does not throw.
- catch sees only errors that are thrown.
Because NaN is a value, not a thrown error.
Did you know?
An error that holds many errors
One kind of error holds a whole list of others. MDN describes AggregateError as the error for when several errors need to be wrapped in a single error: Promise.any, for example, throws it when every task given to it fails. Its errors property is an array of the failures, one for each task. The standard's 2021 edition already defines it.
Why it fits here: It adds one more kind to this topic's list: an error whose job is to carry several other errors at once.
Sources: MDN: AggregateError; ECMAScript 2021 Language Specification
One mistake, two names
The same runaway recursion has different names in different browsers. MDN lists them: Chrome and Safari throw a RangeError, Maximum call stack size exceeded, while Firefox throws an InternalError, too much recursion. InternalError is not in the standard at all, and Firefox's own list of messages files the error under it. So code that checks err.name for one browser can miss the other.
Why it fits here: It warns about this topic's kinds: a few errors come from the engine, not the standard, and their names differ between browsers.
Sources: MDN: InternalError: too much recursion; MDN: InternalError; Firefox source code: ErrorNumbers.msg
In one line
An error is an object with a name, its kind, and a message, what happened; it is thrown up through the running functions. TypeError, ReferenceError, RangeError and SyntaxError are the common kinds, all kinds of Error, while NaN, undefined and Infinity throw nothing.
Throwing an error of your own
At a glance
A railway booking clerk, handed a form with an age of minus three, does not quietly book a ticket for a person who does not exist. The clerk stops and says that the age cannot be right.
A function handed impossible input should do the same. The statement throw new Error("message") stops the function and raises an error of your own, which looks exactly like the language's. Throw an error of the kind that fits, with a message that names the bad value, and never throw a plain string.
Take a guess: If an error is made in one function and thrown in another, where does its trace point?
A railway booking clerk, handed a form with an age of minus three, does not quietly book a ticket for a person who does not exist. He stops and says, "This age cannot be right." A function handed impossible input should do the same: stop, and say plainly what is wrong.
A statement that raises an error on purpose: throw new Error("Age cannot be negative");. The function stops at once, and the error travels back up through the callers until something catches it.
function checkAge(age) {
if (age < 0) {
throw new Error("Age cannot be negative");
}
return age;
}
checkAge(-3);
Uncaught Error: Age cannot be negative
at checkAge (line 3)
at line 7
new Error("...") makes an error object with your message, and throw raises it. The page printed it exactly as it prints JavaScript's own errors, with its trace: thrown in checkAge, at line 3, called from line 7. Your own errors get the same treatment as the language's.
Why throw, instead of returning a message?
The functions lesson's booking function returned the text "At most 6 passengers on one ticket" for a bad booking, and a number otherwise. Every caller then had to check which it got, and a caller that forgot would add the text to a bill. A thrown error cannot be ignored by accident: if nobody catches it, the program stops and says why, at the place where it went wrong.
| Returning a special value | Throwing an error |
|---|---|
| the caller must remember to check | the caller cannot carry on by accident |
| a forgotten check gives a wrong answer later | a missing catch stops the program at once, with a message |
| fits answers that are normal, such as "not found" | fits input that should never happen |
A useful rule: return a value such as null for a result that is ordinary, like a search that finds nothing. Throw for a broken promise: input that breaks a rule, or a step that cannot be done.
The right kind, and a good message
You can throw any of the built-in kinds. Choose the one that fits: TypeError for a value of the wrong type, RangeError for a number outside what is allowed, and Error for a rule of your own. Write the message for the person who will read it in the red line one day, perhaps you:
function parseQty(text) {
const n = Number(text);
if (Number.isNaN(n)) throw new TypeError(`"${text}" is not a number`);
if (n < 1) throw new RangeError("at least 1 ticket");
return n;
}
for (const t of ["2", "two", "0"]) {
try {
console.log(parseQty(t));
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}
2
TypeError: "two" is not a number
RangeError: at least 1 ticket
A good message names the value that was wrong and the rule it broke: "two" is not a number says more than Invalid input. Putting the bad value in quotes shows its exact text, spaces included.
A common mistake
Throwing a plain string. JavaScript lets you throw any value, but a string is not an error object: it has no name, no message and no trace, so the code that catches it cannot ask what kind it is.
try {
throw "oops";
} catch (err) {
console.log(typeof err, err.message);
}
string undefined
Always throw an Error object, made with new. An error can also carry the reason behind it in a second argument, { cause: ... }, which MDN describes:
const err = new Error("Fare missing", { cause: "harbour line" });
console.log(err.message, err.cause);
Fare missing harbour line
Worked example 2
A UPI app's function sends money. An amount of zero or less, or more than ₹1,00,000, must never be sent. Write the check with throw, and try it on 500, 0 and 2,00,000.
What we have: an amount, and two limits
What we need: the amount for a good payment, and a clear error for a bad one
The plan: check each rule at the top of the function and throw a RangeError naming the amount; then try three amounts, catching to print each message
function send(amount) {
if (amount <= 0) throw new RangeError(`cannot send ₹${amount}`);
if (amount > 100000) throw new RangeError(`₹${amount} is over the ₹1,00,000 limit`);
return `Sent ₹${amount}`;
}
for (const a of [500, 0, 200000]) {
try {
console.log(send(a));
} catch (err) {
console.log(err.message);
}
}
Sent ₹500
cannot send ₹0
₹200000 is over the ₹1,00,000 limit
₹500 is sent; ₹0 and ₹2,00,000 are refused, each with a message.
Check: 500 passes both rules; 0 breaks the first; 2,00,000 breaks the second.
A path that fails: returning false for a bad amount. A caller that writes send(0); and forgets to look at the answer believes the money went.
When you are stuck: deciding when to throw
Throw for input or a state that should never happen; return a value for an ordinary outcome, such as nothing found.
Choose the kind: TypeError for the wrong type, RangeError for a number out of bounds, Error otherwise.
Write the message as a sentence for the reader of the red line, naming the bad value.
Always throw an object made with new Error, never a plain string.
Your turn
function half(n) {
if (typeof n !== "number") throw new TypeError("half needs a number");
return n / 2;
}
try {
console.log(half(8));
console.log(half("8"));
} catch (err) {
console.log(err.message);
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
half needs a number
- half(8) passes the check and prints 4.
- half("8") gets a string, so it throws.
- The catch prints the message, and nothing else in try runs.
It prints 4, then half needs a number.
Which kind of error fits a seat number of 500 in a hall of 120 seats?Tap to reveal
- The value is a number, so its type is right.
- It is outside the allowed range.
A RangeError.
Why is throw new Error("...") better than throw "..."?Tap to reveal
- An Error object has a name, a message and a trace.
- A string has none of them, so catch cannot ask what it is.
Because an Error object carries its name, message and trace.
Did you know?
The trace is made at new
An error's trace is written when the error is made, not when it is thrown. V8, the engine in Chrome and Node.js, says the trace is collected when the error is created, and stays the same wherever, and however often, the error is thrown. ESLint's guide gives this as the reason to throw Error objects: they keep track of where they were built.
Why it fits here: It explains this topic's rule against throwing a plain string: only an Error object records where it was built.
Sources: V8: Stack trace API; ESLint: no-throw-literal
The standard's own RangeError
The standard throws RangeError too, for numbers outside what a function allows. The method toFixed, which rounds a number to a set count of decimal places, takes from 0 to 100 digits. MDN notes that any other count throws a RangeError, and the standard's own steps say the same. So (2.5).toFixed(101) stops with an error instead of guessing.
Why it fits here: It is a model for this topic's choice of kind: a number outside the allowed range is a RangeError, in the standard's own code.
Sources: MDN: Number.prototype.toFixed(); ECMAScript Language Specification: Number.prototype.toFixed
In one line
throw new Error("message") stops a function and raises an error of your own, which looks exactly like the language's. Throw for input that breaks a rule, of the kind that fits, with a message that names the bad value; never throw a plain string.
Catching: try, catch and finally
At a glance
A circus acrobat works above a net. The net does not stop a fall; it catches the acrobat when one happens, so that the show can go on. The words try and catch are the net of a program.
In a program, try runs a block, and if anything in it throws, catch runs with the error. The block finally runs after both, every time, even after a return. A try stops at the throw, and a catch around a call catches errors thrown anywhere inside it.
Take a guess: If try returns one value and finally returns another, which one does the function give back?
A circus acrobat works above a net. The net does not stop her falling; it catches her when she does, so that the show can go on. try and catch are the net of a program.
A statement in two blocks: the code in try { ... } runs, and if anything in it throws, the rest of the try block is skipped and the catch (err) { ... } block runs, with the error in the name err. If nothing throws, the catch block is skipped.
try {
console.log("trying");
throw new Error("boom");
} catch (err) {
console.log("caught", err.message);
} finally {
console.log("finally");
}
trying
caught boom
finally
Read the order of the output. The try block ran until the throw. Control jumped straight to catch, which printed the message. Then the finally block ran. finally runs every time, whether the try succeeded, or failed and was caught. It is for clean-up that must always happen, such as hiding a Loading message or closing a file.
A try stops at the throw
Nothing in the try block after the line that throws is run, and nothing before it is undone. A value changed before the throw stays changed:
let x = 5;
try {
x = 10;
throw new Error("stop");
x = 20;
} catch {
console.log(x);
}
10
x became 10, then the throw jumped to catch, so x never became 20. This catch has no name in brackets, catch { ... }, which is allowed when the block does not need the error object.
finally runs even after a return
function f() {
try {
return "from try";
} finally {
console.log("finally ran");
}
}
console.log(f());
finally ran
from try
The return was waiting to hand back its value when finally ran. That is what makes finally safe for clean-up: no return and no error can skip it.
An error travels up to the nearest catch
An error thrown deep inside function calls travels back up the call stack of the functions lesson, through each caller, until it reaches a try. A catch around a call catches errors thrown anywhere inside that call, callbacks included:
try {
[1, 2, 3].forEach((n) => {
if (n === 2) throw new Error(`bad item ${n}`);
});
} catch (err) {
console.log(err.message);
}
bad item 2
The error was thrown inside the arrow, called by forEach, called inside try. It travelled up through both, out of the forEach, to the catch. Item 3 was never reached.
Worked example 3
A delivery app loads a list of orders from JSON text, and must show a Loading... message while it works and remove it afterwards, whether the text was good or broken. Write it with try, catch and finally, and try it on broken text.
What we have: JSON text that may be broken, and a status message
What we need: the orders or a clear failure, and the status cleared in both cases
The plan: parse in try; report the problem in catch; clear the status in finally
function load(text) {
let status = "Loading...";
try {
const orders = JSON.parse(text);
console.log(`${orders.length} orders`);
} catch (err) {
console.log(`Could not read the orders: ${err.name}`);
} finally {
status = "";
console.log(`status is now "${status}"`);
}
}
load('[{"id": 1}, {"id": 2}]');
load("[{bad");
2 orders
status is now ""
Could not read the orders: SyntaxError
status is now ""
Good text gives 2 orders; broken text gives a clear message; the status is cleared both times.
Check: the finally line printed after each call, once after success and once after the caught SyntaxError.
A path that fails: clearing the status at the end of the try block. When the text is broken, the throw skips that line, and the page shows Loading... for ever.
When you are stuck: a catch does not catch, or catches too much
catch only sees errors thrown while its try block runs; an error before the try, or a SyntaxError in the code itself, never reaches it.
Code after the throwing line in try never runs, so put clean-up in finally.
If a catch hides every error, print err.name and err.message in it, so that a new kind of error is noticed.
Errors travel up through callers, so one try around a call covers everything inside it.
Your turn
try {
console.log("a");
JSON.parse("{");
console.log("b");
} catch {
console.log("c");
} finally {
console.log("d");
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a
c
d
- a prints first.
- JSON.parse throws, so b is skipped.
- catch prints c, and finally prints d.
It prints a, c, d.
When does a finally block run?Tap to reveal
- After try, whether it threw or not, and after catch if it ran.
- Even when try or catch returns.
Every time.
Can try { ... } catch { ... } catch a missing bracket in its own try block?Tap to reveal
- A missing bracket is a SyntaxError in the code itself.
- Such a program never starts, so no catch runs.
No: the program cannot even start.
Did you know?
A return in finally wins
A return inside finally beats every other return. MDN explains that a return in the try block is held back while finally runs, and a return in finally then overrides it, value and all. Even a planned throw gives way, and the function returns instead. ESLint's guide calls this unexpected behaviour, and its recommended rules forbid return, throw, break and continue in finally.
Why it fits here: It answers this topic's question about two returns: the one in finally wins, which is why finally should only clean up.
Sources: MDN: try...catch; ESLint: no-unsafe-finally
finally began as unwind-protect
The block that always runs is older than JavaScript. Wikipedia traces the clean-up now called finally to NIL, a Lisp of the mid to late 1970s, where it was UNWIND-PROTECT. Common Lisp kept the name: its standard says unwind-protect guarantees that the clean-up forms run, whether the protected form ends normally or is aborted. The name says it: protect the clean-up while unwinding.
Why it fits here: It gives this topic's finally a history: the promise to run clean-up code, whatever happens, was made in Lisp first.
Sources: Wikipedia: Exception handling (programming); Common Lisp HyperSpec: Special Operator UNWIND-PROTECT
In one line
try runs a block, and if anything in it throws, catch runs with the error; finally runs after both, every time, even after a return. A try stops at the throw, and a catch around a call catches errors thrown anywhere inside it.
Where to catch, and where to let it fly
At a glance
A hospital does not ask every nurse to perform surgery. A nurse who finds a problem that cannot be treated on the ward passes it on, quickly and in plain words, to someone who can.
Code handles errors the same way. Catch only where you can do something useful: fall back for the kind you can handle, and rethrow the rest. Catch at the edges, where a person is waiting, and never leave a catch empty. When one bad item must not stop the rest, put the try inside the loop.
Take a guess: Why might a catch that hides every error make a program harder to fix?
A hospital does not ask every nurse to perform surgery. A nurse who finds a problem she cannot treat passes it on, quickly and in plain words, to someone who can. Errors are handled the same way: each piece of code catches only what it can do something useful about, and lets everything else go on up.
Catch only what you can handle
A function that reads saved settings can deal sensibly with one problem: the saved text is broken. It can fall back to no settings. Any other error, such as a slip in its own code, it cannot fix, and should not hide. So it catches, checks the kind, and throws the rest on, with a bare throw err;, which is called rethrowing:
function load(text) {
try {
return JSON.parse(text);
} catch (err) {
if (err instanceof SyntaxError) {
return null;
}
throw err;
}
}
console.log(load('{"a":1}'), load("{bad"));
{ a: 1 } null
Broken text gives null, an ordinary answer the caller can test. A different kind of error would leave the function exactly as it arrived, to be seen by someone who can deal with it.
A common mistake
Catching everything and doing nothing. try { ... } catch {} with an empty catch is called swallowing an error. The program carries on as if all were well, with a value missing or half a job done, and the red line that would have named the slip is gone. Every catch should do something: fall back, report, or rethrow.
Catch at the edges
Most functions should not catch at all. They throw when their rules are broken, and let the error travel up. The place to catch is near the edge of the program, where a person or another system is waiting: the handler for a button, the code that draws a page, the part of a server that answers a request. There, the error can become a clear message, and the rest of the program can carry on.
function b() {
throw new Error("deep");
}
function a() {
b();
}
try {
a();
} catch (err) {
console.log("shown to the user:", err.message);
}
a();
shown to the user: deep
Uncaught Error: deep
at b (line 2)
at a (line 5)
at line 12
Neither a nor b catches. The first call is wrapped in try at the edge, so the error becomes a message. The second call is not, so the error goes all the way up, and the page prints it with its full trace: thrown in b, called from a, called from line 12. That trace is exactly what you want while building: it names every step.
| Where | Catch? | Why |
|---|---|---|
| a small function that checks its input | no: throw | it cannot know what the caller wants to do about it |
| a function that can fall back sensibly | yes, for that one kind; rethrow the rest | it can turn one failure into an ordinary answer |
| an event handler, or the code that draws a page | yes | a person is waiting, and the rest of the page should keep working |
| anywhere, with an empty catch | never | it hides the slip |
Worked example 4
The harbour board of the story draws every ferry from the timetable. One bad line must not stop the others. Catch each line's error at the edge, the loop that draws the board, and show a note for that line only.
What we have: three timetable lines, one of them broken
What we need: two ferries drawn, and a note for the broken line
The plan: a small function reads one line and throws for a bad one; the loop catches each line's error separately and carries on
function readTime(line) {
if (!/^\d{1,2}\.\d{2}$/.test(line)) {
throw new Error(`${line} could not be read`);
}
return line;
}
const board = [];
for (const line of ["4.15", "4..15", "5.30"]) {
try {
board.push(`Ferry at ${readTime(line)}`);
} catch (err) {
board.push(`${err.message}, please ask at the counter`);
}
}
console.log(board.join("\n"));
Ferry at 4.15
4..15 could not be read, please ask at the counter
Ferry at 5.30
- The test
/^\d{1,2}\.\d{2}$/is a regular expression, a pattern for text: one or two digits, a dot, two digits. The modern JavaScript step meets such patterns again. Here it only answers: does the line look like a time?
The board shows 4.15 and 5.30, and one note for the damaged line.
Check: three lines in, three rows out, and the bad one named in its own row.
A path that fails: putting one try around the whole loop. The first bad line then jumps to the catch, the loop ends there, and 5.30 is never drawn: the board of the story goes dark again, after one row.
When you are stuck: an error is hidden, or stops too much
If an error vanished, look for an empty catch, or one that catches every kind and does nothing.
If one bad item stops a whole list, move the try inside the loop, around one item.
In a catch that can handle one kind, test with instanceof and rethrow the rest.
Catch near a person or a request; elsewhere, let the error go up with its trace.
Your turn
What does throw err; do inside a catch block?Tap to reveal
- It raises the same error again.
- The error goes on up, to a catch further out, or to the top.
It rethrows the error for someone else to handle.
Why is catch {} with an empty block dangerous?Tap to reveal
- It stops the error and does nothing about it.
- The slip is hidden, and the program carries on with a missing value.
Because it swallows the error.
A list of 100 orders is drawn in a loop, and one order is broken. Where should the try go so that the other 99 are drawn?Tap to reveal
- A try around the whole loop stops at the first broken order.
- A try inside the loop, around one order, lets the loop carry on.
Inside the loop, around each order.
Did you know?
An error with a cause
A new error made in a catch can now keep the old one. Since ECMAScript 2022, an error can carry its cause: new Error("Settings are broken", { cause: err }). MDN explains that cause is used when catching and rethrowing an error with a more useful message, while keeping access to the original error. TC39's list of finished proposals names the people behind it, Chengzhong Wu and Hemanth HM.
Why it fits here: It improves this topic's rethrow: the new error can keep the old one as its cause, so nothing is lost on the way up.
Sources: MDN: Error: cause; ECMAScript 2022 Language Specification; TC39: Finished Proposals
Why catch and throw were made
The words catch and throw were born from a swallowed error. In MacLisp, an early Lisp, programmers used the error trap ERRSET for jumps that had nothing to do with errors, and it quietly trapped unexpected errors too, making programs harder to debug. So in June 1972 MacLisp gained a new pair, CATCH and THROW, and ERRSET went back to trapping errors only.
Why it fits here: It is this topic's rule in its oldest form: a catch that traps every error hides the ones nobody expected.
Sources: Guy L. Steele Jr. and Richard P. Gabriel: The Evolution of Lisp; Wikipedia: Exception handling (programming)
In one line
Catch only where you can do something useful: fall back for the kind you can handle and rethrow the rest, and catch at the edges where a person is waiting. Never leave a catch empty, and put the try around each item when one bad item must not stop the rest.
Checking at the edges: loud and early
At a glance
At a railway station, tickets are checked at the gate, not in the middle of the journey. A passenger without one is stopped there, with a clear word, before any harm is done.
A program has gates too: the places where data enters it, from a person, a file or another computer. Check the data there, and throw a named error for anything that breaks the rules. A quiet wrong answer then becomes a loud, early error next to its cause. While you build, console.assert checks your own beliefs about the code.
Take a guess: Who first suggested checking a program with assertions, and in which year?
At a railway station, tickets are checked at the gate, not in the middle of the journey. A passenger without one is stopped there, with a clear word, before any harm is done. A program has gates too: the places where data enters it, from a person, a file or another computer. That is where to check it.
The values lesson showed how quiet a wrong value can be: an empty box becomes 0, a word becomes NaN, a missing field becomes undefined, and the program carries on. Each of these surfaces far from where it entered, as a wrong total in a bill or a blank on a page. Checking at the gate turns a quiet wrong answer into a loud, early error, at the place that caused it.
function readQty(text) {
const n = Number(text);
if (text.trim() === "" || Number.isNaN(n)) {
throw new TypeError(`quantity "${text}" is not a number`);
}
return n;
}
function bill(qtyText, price) {
return readQty(qtyText) * price;
}
try {
console.log(bill("3", 45));
console.log(bill("", 45));
} catch (err) {
console.log(err.message);
}
135
quantity "" is not a number
Without the check, an empty box would have given a bill of 0, silently. With it, the error names the bad value, and the place: readQty, the gate. Everything after the gate can trust that the quantity is a real number.
Fail fast
Stopping at the first sign of a bad value, rather than carrying on and hoping, is called failing fast. It sounds harsh, but it makes bugs cheap: the error appears next to its cause, during testing, rather than as a strange number in a customer's bill weeks later.
Assertions while you build
While building, you can also write down what you believe is true at a point, and be told if it is not. console.assert(condition, message) prints the message, marked as a failed assertion, only when the condition is false, and lets the program carry on:
const total = 120 + 45;
console.assert(total === 165, "the total is wrong");
console.assert(total > 200, "the total is under 200");
console.log("carried on");
Assertion failed: the total is under 200
carried on
Assertions are notes to yourself, checked as the program runs. The testing steps of this path, later, turn the same idea into tests that run on every change.
| Tool | When | What happens when it fails |
|---|---|---|
| a check that throws | data entering the program | the program stops there, with a named error |
console.assert | beliefs while you build | a line in the Console; the program carries on |
?. and ?? | data that may honestly be missing | a default instead of an error |
Worked example 5
A school's admission form sends a date of birth as text, such as 2010-05-14. Check it at the gate: the text must have four digits, a dash, two digits, a dash, two digits, and the month must be from 1 to 12. Throw a clear error otherwise, and test three entries.
What we have: dates as text, from a form
What we need: the date accepted, or a named error for each bad one
The plan: split the text at the dashes, check the parts' lengths and the month's range, and throw a TypeError or a RangeError
function readDate(text) {
const parts = text.split("-");
if (parts.length !== 3 || parts[0].length !== 4 || parts[1].length !== 2 || parts[2].length !== 2) {
throw new TypeError(`"${text}" is not written as YYYY-MM-DD`);
}
const month = Number(parts[1]);
if (month < 1 || month > 12) {
throw new RangeError(`month ${month} does not exist`);
}
return text;
}
for (const d of ["2010-05-14", "14/05/2010", "2010-13-01"]) {
try {
console.log("ok", readDate(d));
} catch (err) {
console.log(err.name, err.message);
}
}
ok 2010-05-14
TypeError "14/05/2010" is not written as YYYY-MM-DD
RangeError month 13 does not exist
The first date is accepted; the other two are refused with errors that name the problem.
Check: 14/05/2010 has no dashes, so split gives one part; 13 is not a month.
A path that fails: accepting the text and checking it later, where the date is used. A form that sends 2010-13-01 is then stored, and fails months later, in a report, far from the form that caused it.
When you are stuck: a bad value turns up far from where it came in
Find where the value entered the program: a box, a file, a reply from a server.
Add a check there that throws a named error for anything outside the rules.
Use console.assert while building to be told when a belief about a value is wrong.
Use ?. and ?? only for values that may honestly be missing, not to hide broken ones.
Your turn
console.assert(2 + 2 === 4, "maths is broken");
console.assert("5" === 5, "a string is not a number");
console.log("done");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Assertion failed: a string is not a number
done
- The first assertion is true, so it prints nothing.
- The second is false, so its message is printed.
- Neither stops the program.
It prints Assertion failed: a string is not a number, then done.
Where should a program check the age typed into a form?Tap to reveal
- At the gate: where the text enters, before it is used.
- Then everything after can trust it.
Where it enters, in the function that reads the form.
What does failing fast mean?Tap to reveal
- Stopping at the first sign of a bad value.
- So the error appears next to its cause.
Stopping early, with a clear error, rather than carrying on with a bad value.
Did you know?
Assertions, 1949
The idea of stating what must be true at each step goes back to 1949. At a Cambridge conference in June that year, held for the launch of the EDSAC computer, Alan Turing gave a talk called Checking a Large Routine. Turing suggested that the programmer should make a number of definite assertions, each checked on its own, from which the correctness of the whole program follows.
Why it fits here: It gives this topic's console.assert a famous ancestor: checking a program by stating, step by step, what must be true.
Sources: Wikipedia: Assertion (software development); arXiv: 1904.03917; Xavier Leroy, Collège de France: course slides
Failing slowly
In 2004 Jim Shore gave this topic's idea a name in IEEE Software: fail fast. A program that works around problems by itself ends up failing slowly, carrying on after an error and failing in strange ways later. A fail-fast system, as Wikipedia defines it, immediately reports at its interface any condition likely to indicate a failure. It sounds fragile, Shore wrote, but it makes software more robust.
Why it fits here: It names this topic's habit: stop at the first sign of bad data, close to its cause, instead of carrying on.
Sources: Jim Shore: Fail Fast, IEEE Software; Wikipedia: Fail-fast system
In one line
Check data at the gates where it enters a program, and throw a named error for anything that breaks the rules. A quiet wrong answer then becomes a loud, early error next to its cause. The console.assert line checks your own beliefs while you build.
The method, on a whole program
At a glance
A canteen's customer ordered a lassi at ₹45 and a dosa at ₹90, so the bill should be ₹135. The printed bill said ₹4590. Nothing threw, and no error appeared in the console.
For a bug like this, follow the method. Reproduce it with its own input, and cut it down. Print each step with typeof until the first wrong value appears. Fix the cause at the gate, and check the fix with good and bad input. Every tool of this track meets here: typeof, the trace, the Console and breakpoints.
Take a guess: How many lines of a crashing web page did one tool need to keep, out of 896?
The Learning to learn step gave you a method for any bug: read the message, reproduce the bug, cut it down, print to see, fix, and check the fix. Every lesson of this track has added tools to it: typeof, the trace, the Console, breakpoints, and now error objects. This section puts them together on a program with a bug that throws nothing.
A canteen's customer ordered a lassi at ₹45 and a dosa at ₹90, so the bill should be ₹135. The printed bill said ₹4590. There was no error and no red line: only a wrong answer.
The developer first runs the billing code on a test order kept for checking, two thalis and a lassi:
const items = [
{ name: "thali", price: "90", qty: 2 },
{ name: "lassi", price: 45, qty: 1 },
];
function lineTotal(item) {
return item.qty === 1 ? item.price : item.price * item.qty;
}
function billTotal(list) {
let total = 0;
for (const item of list) {
total += lineTotal(item);
}
return total;
}
console.log(`Bill: ₹${billTotal(items)}`);
Bill: ₹225
₹225 is right for that order. So the test order does not show the bug, and any change made now could not be checked. That is the first rule of debugging: reproduce the bug, with the input that caused it, before changing anything. The customer's order was a lassi and a dosa, one of each:
const items = [
{ name: "lassi", price: 45, qty: 1 },
{ name: "dosa", price: "90", qty: 1 },
];
function lineTotal(item) {
return item.qty === 1 ? item.price : item.price * item.qty;
}
function billTotal(list) {
let total = 0;
for (const item of list) {
total += lineTotal(item);
}
return total;
}
console.log(`Bill: ₹${billTotal(items)}`);
Bill: ₹4590
Reproduced: ₹4590. Now cut the case down to the loop alone, and print to see, at each step, with labels and with typeof:
const items = [
{ name: "lassi", price: 45, qty: 1 },
{ name: "dosa", price: "90", qty: 1 },
];
function lineTotal(item) {
return item.qty === 1 ? item.price : item.price * item.qty;
}
let total = 0;
for (const item of items) {
const line = lineTotal(item);
console.log(item.name, line, typeof line);
total += line;
console.log("total now", total, typeof total);
}
lassi 45 number
total now 45 number
dosa 90 string
total now 4590 string
There it is. An item with a quantity of 1 skips the multiplication, so its text price, "90", is returned as text. Adding text to a number joins them: 45 and "90" make 4590. The bug needed two things at once: a price saved as text, and a quantity of 1. The prints, with typeof, showed the first wrong value: a line total whose type was string.
Now the fix belongs at the gate, as the last section said: convert, and check, each price where the items enter the program, so that every function after it can trust them.
function readItem(raw) {
const price = Number(raw.price);
if (Number.isNaN(price)) throw new TypeError(`price of ${raw.name} is not a number`);
return { name: raw.name, price, qty: raw.qty };
}
const items = [
{ name: "lassi", price: 45, qty: 1 },
{ name: "dosa", price: "90", qty: 1 },
].map(readItem);
const total = items.reduce((s, i) => s + (i.qty === 1 ? i.price : i.price * i.qty), 0);
console.log(`Bill: ₹${total}`);
Bill: ₹135
| Step | What you did here | The tool |
|---|---|---|
| read | no message: a wrong answer, ₹4590 for ₹135 | the report itself |
| reproduce | found the input that shows it: a text price with a quantity of 1 | trying the program with different items |
| cut down | two items, one function | removing everything that still showed the bug without |
| print to see | the first value of the wrong type | labelled prints with typeof |
| fix at the cause | convert and check at the gate | a reading function that throws |
| check the fix | the bill is ₹135, and a bad price now throws | running it again, with good and bad items |
In the browser, the Sources panel of the DevTools step does the printing for you. A breakpoint inside the loop, with the condition typeof line === "string", stops at exactly the round where the wrong type first appears, and the Scope pane shows every value. The method is the same; only the tool is faster.
Worked example 6
A results script stops with a red line: Uncaught TypeError: Cannot read properties of undefined (reading 'total'). Use the method to find the slip and fix it.
What we have: the script and its red line
What we need: the cause, and a fix that names the problem if it ever happens again
The plan: read the message and the trace's top line; print the value the message is about; fix the cause where the name enters
const results = { asha: { total: 412 }, ravi: { total: 389 } };
function totalFor(name) {
return results[name].total;
}
console.log(totalFor("asha"));
console.log(totalFor("Ravi"));
412
Uncaught TypeError: Cannot read properties of undefined (reading 'total')
at totalFor (line 3)
at line 6
- Read: a TypeError, reading total from undefined, thrown in totalFor at line 3, for the call at line 6. So
results[name]was undefined for that call. - Print what the message is about: the keys, and the value for the name used at line 6.
const results = { asha: { total: 412 }, ravi: { total: 389 } };
console.log(Object.keys(results), results["Ravi"]);
[ 'asha', 'ravi' ] undefined
- The keys are written in small letters, and the call used Ravi with a capital. Fix it where the name enters: bring it to small letters, and throw a named error for a name that is not there.
const results = { asha: { total: 412 }, ravi: { total: 389 } };
function totalFor(name) {
const key = name.toLowerCase();
if (!(key in results)) throw new Error(`no results for ${name}`);
return results[key].total;
}
console.log(totalFor("Ravi"));
389
The cause was a capital letter: the key is ravi, not Ravi. The fixed function gives 389.
Check: an unknown name now stops with no results for, and the name, instead of a TypeError about total.
A path that fails: wrapping the line in a try with an empty catch. The script stops crashing, and Ravi's total is quietly missing from the page.
When you are stuck: a bug throws no error
Reproduce it first: find the input that shows it, or you may fix the wrong thing.
Print each step's value with typeof, and a label, and find the first one that is wrong.
Cut the case down to the smallest program that still shows the bug.
Fix the cause, usually where the bad value entered, and check the fix with good and bad input.
Your turn
Why reproduce a bug before fixing it?Tap to reveal
- Without the input that shows it, you cannot tell whether a change fixed anything.
- You might change code that was never broken.
Because only the bug's own input can show that a fix works.
A line total prints as 90 with typeof string. What will happen when it is added to a total of 45?Tap to reveal
- One side is a string, so + joins.
- 45 and "90" make the text 4590.
The total becomes the text 4590.
Where should the conversion of a price from text happen?Tap to reveal
- Where the data enters the program.
- Then every function after can trust that the price is a number.
At the gate, where the items are read.
Did you know?
896 lines cut to one
Cutting a bug down can be done by a program. In 1999 Andreas Zeller of Saarland University described delta debugging, which narrows down what makes a program fail until a minimal set remains. In one case study, a web page that made the Mozilla browser fail had 896 lines of HTML. The method cut them down to the single line that caused the failure.
Why it fits here: It automates this topic's cut-it-down step: a program tries smaller and smaller inputs until only the cause is left.
Sources: Wikipedia: Delta debugging; Andreas Zeller and Ralf Hildebrandt: Simplifying and Isolating Failure-Inducing Input
Steps, expected, actual
Browser makers ask for this method in every bug report. Mozilla's bug writing guidelines ask for precise steps to reproduce, the expected results and the actual results. If a bug shows up only now and then, they say, the reporter must give more information for the report to be useful. A fix can only be checked against a bug that can be made to happen again.
Why it fits here: It shows this topic's first step in real use: a bug report begins with the input and steps that make the bug happen.
Source: Mozilla: Bug Writing Guidelines
In one line
For a bug that throws nothing, follow the method. Reproduce it with its own input, and cut it down. Print each step with typeof until the first wrong value appears, fix the cause at the gate, and check the fix with good and bad input.
Where it is used
Every real program meets bad data and broken parts. Here is where each idea of this lesson shows up in real work.
| What you learned | Where it is used | A real example |
|---|---|---|
| error names and messages | reading what went wrong | a server's log line: TypeError: Cannot read properties of undefined (reading 'email') |
| throw with a clear message | rules a program must keep | a payment function that refuses an amount of ₹0 |
| try and catch at the edges | pages and servers that must keep working | a board that draws every ferry it can read, and notes the one it cannot |
| finally | clean-up that must always happen | hiding a Loading message whether the request worked or not |
| rethrowing | handling one kind, passing on the rest | a settings loader that falls back for broken text only |
| checking at the gate | every form and every reply from another system | an admission form that refuses a month of 13 |
| console.assert | beliefs checked while building | a note that a total must never be negative |
| the method | every bug, every day | finding the text price that turned ₹135 into ₹4590 |
Mistakes and debugging
These are the slips that people meet most often with errors. Every output below is the real one, from the code shown.
1. An empty catch
let settings = { theme: "light" };
try {
settings = JSON.parse("{bad");
} catch {}
console.log(settings.theme);
light
No error, and no clue that the saved settings were broken. The fix: do something in every catch: fall back on purpose and say so, or rethrow.
2. Throwing a string
try {
throw "Fare missing";
} catch (err) {
console.log(err.name, err.message);
}
undefined undefined
The fix: throw new Error("Fare missing"), which has a name, a message and a trace.
3. One try around a whole list
const out = [];
try {
for (const t of ["4.15", "x", "5.30"]) {
if (t === "x") throw new Error("bad line");
out.push(t);
}
} catch (err) {
out.push(err.message);
}
console.log(out.join(", "));
4.15, bad line
No error shown, but 5.30 was never reached. The fix: move the try inside the loop, around one item.
4. Clean-up placed in try
let loading = true;
try {
JSON.parse("{bad");
loading = false;
} catch {
console.log("failed");
}
console.log(loading);
failed
true
The fix: put loading = false; in a finally block, which runs every time.
5. Expecting catch to see NaN
try {
const total = Number("ninety") * 2;
console.log(total);
} catch {
console.log("caught");
}
NaN
No error was thrown, so catch never ran. The fix: check the value and throw: if (Number.isNaN(total)) throw new TypeError(...).
6. An error that nobody catches
function send(amount) {
if (amount <= 0) throw new RangeError(`cannot send ₹${amount}`);
return "sent";
}
send(0);
Uncaught RangeError: cannot send ₹0
at send (line 2)
at line 5
Here the red line is doing its job while you build: it names the kind, the message and the line. The fix: catch it at the edge, where a person is waiting, and turn it into a message for them.
The debugging corner: read the error object
In a catch, print err.name and err.message first, every time. The name tells you the kind of slip, and the message usually names the value or property at fault. The stack property holds the trace as text; MDN marks it as non-standard, as each runtime writes it in its own way, so read it in the Console rather than in your program. The DevTools step's Sources panel can also pause on every exception, caught ones included, which finds an empty catch at once.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
// throw your own error: the right kind, a message that names the bad value
function readQty(text) {
const n = Number(text);
if (text.trim() === "" || Number.isNaN(n)) throw new TypeError(`"${text}" is not a number`);
if (n < 1) throw new RangeError("at least 1");
return n;
}
// catch at the edge, item by item; finally always runs
const shown = [];
for (const t of ["2", "two", "0"]) {
try {
shown.push(readQty(t));
} catch (err) {
shown.push(`${err.name}: ${err.message}`);
} finally {
shown.push("|");
}
}
console.log(shown.join(" "));
// handle one kind, rethrow the rest
function load(text) {
try {
return JSON.parse(text);
} catch (err) {
if (err instanceof SyntaxError) return null;
throw err;
}
}
console.log(load("[1]"), load("{bad"));
// beliefs while building
console.assert(1 + 1 === 2, "never printed");
2 | TypeError: "two" is not a number | RangeError: at least 1 |
[ 1 ] null
| When you see | It means | Look at |
|---|---|---|
| Uncaught and a name, message and trace | an error nobody caught | the top line of the trace; catch it at the edge |
| a wrong answer, and no error | a quiet value: NaN, undefined, text for a number | print each step with typeof; check at the gate |
| undefined undefined from err.name and err.message | a plain string was thrown | throw new Error(...) |
| a list that stops after the first bad item | one try around the whole loop | a try around each item |
| Loading... that never goes away | clean-up inside try | finally |
| a problem that never shows | an empty catch | fall back on purpose, report, or rethrow |
The story: A bad gear, named and set aside
You teach the board to check each line of the timetable as it arrives. A line that cannot be read is set aside, with a plain note in the diary that names the line and says what was wrong with it. Every other line is drawn as before.
The board lights up, every ferry in its place, and one row reads: 4..15 could not be read, please ask at the counter.
Master Verge looks along the board, then at you. "The Clock Tower's ground floor is yours," he says. "Upstairs, the clocks learn to wait for things that have not happened yet."
Reagents gathered: Error, throw, try, catch, finally, stack trace.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)