Errors: throw, try, catch and finally
A thrown error is the way a JavaScript function says that it cannot do what was asked. It stops the call at once, leaves the frames above it, and runs the first catch that the call went through. A program that has none ends: Node.js prints the error on standard error and exits with a code that a script can test.
This lesson takes the three parts in turn: the throw statement and what a program without a handler does, the try and catch around it, and the finally block that runs either way. The last section reads the Error object itself, which is what the two lessons after this one extend.
throw stops the call
throw takes any value and abandons the current function, the caller and every frame between them, until a handler takes it. The function below refuses an empty name, and the caller catches the refusal and carries on with the next line: the frame that threw does not return a value at all.
The file throw.mjs:
function load(name) {
if (name === '') {
throw new Error('the name is empty');
}
return `loaded ${name}`;
}
console.log(load('notes.txt'));
try {
console.log(load(''));
console.log('this line does not run');
} catch (error) {
console.log('caught:', error.message);
}
console.log('the program goes on');
node throw.mjs
loaded notes.txt
caught: the name is empty
the program goes on
The line after the failing call never ran, and neither did the value it would have printed. What did run is the catch block, and after it the program continued as if nothing had happened. That is the whole shape of error handling in the language: a value leaves a function by a second door, and the caller decides what to do with it.
Without a handler at all, the second door leads out of the program. The file below throws in the middle and has nothing to catch it, so Node.js prints the stack on standard error and exits with one.
The file uncaught.mjs:
console.log('before the call');
function fail() {
throw new Error('the disk is full');
}
fail();
console.log('this line never runs');
node uncaught.mjs
echo "exit code: $?"
before the call
exit code: 1
The message Error: the disk is full and the stack below it went to standard error, which is why the block above does not show them: the text of a stack has file paths and line numbers that belong to one machine. What a script reads is the exit code, and an uncaught error always means one.
try and catch
try marks the code whose failures the block below handles, and catch receives whatever was thrown. Any value can be thrown, so the variable in parentheses may hold a string, a number or an Error, and the code that reads it has to know which. The program below throws both kinds and looks at what arrives.
The file any.mjs:
try {
throw 'just a string';
} catch (error) {
console.log('what arrived:', error);
console.log('its type:', typeof error);
console.log('it has no message:', error.message === undefined);
}
function read(name) {
if (name === '') {
throw new TypeError('the name must be a string with letters');
}
return name.toUpperCase();
}
try {
read('');
} catch (error) {
console.log('the name of the error:', error.name);
console.log('the message of the error:', error.message);
}
node any.mjs
what arrived: just a string
its type: string
it has no message: true
the name of the error: TypeError
the message of the error: the name must be a string with letters
The string arrived as a string, so error.message was the field of a string, which is undefined: nothing failed, and the log line quietly printed nothing useful. A thrown string cannot say where it came from either. The second throw used TypeError, which is one of the built-in error classes, and that value carries a name, a message and a stack.
finally always runs
A finally block runs after the try whether it finished, threw or returned. That makes it the place for the step that must happen in every case, such as closing what was opened, and it is why the block runs before the value of a return leaves the function.
The file finally.mjs:
function read(name) {
console.log('open', name);
try {
if (name === 'missing.txt') {
throw new Error('no such file');
}
return 'contents';
} catch (error) {
console.log('caught:', error.message);
return 'fallback';
} finally {
console.log('close', name);
}
}
console.log(read('notes.txt'));
console.log(read('missing.txt'));
node finally.mjs
open notes.txt
close notes.txt
contents
open missing.txt
caught: no such file
close missing.txt
fallback
Both calls printed close before the value of the function, once on the way out of the try and once on the way out of the catch. The return inside a finally would replace the value of the outer return, so a block that has one swallows the result and the error alike, which is the one mistake to avoid here.
The Error class
new Error(message) builds an object with three fields worth knowing: name, which is the name of the class, message, which is the text of the constructor argument, and stack, which is the trace as one string that starts with the name and the message. The built-in classes TypeError, RangeError and the rest are the same object with another name.
The file error.mjs:
const error = new Error('bad input');
console.log('message:', error.message);
console.log('name:', error.name);
console.log('is an Error:', error instanceof Error);
console.log('the first line of the stack:', error.stack.split('\n')[0]);
const type = new TypeError('not a number');
const range = new RangeError('out of range');
console.log('TypeError is an Error:', type instanceof Error);
console.log('RangeError is an Error:', range instanceof Error);
console.log('the built-in names:', type.name, range.name);
node error.mjs
message: bad input
name: Error
is an Error: true
the first line of the stack: Error: bad input
TypeError is an Error: true
RangeError is an Error: true
the built-in names: TypeError RangeError
The first line of the stack is the name and the message, so a log line that prints the whole error prints the two together, and the frames come after it. Everything here is a promise about the next two lessons: a name that a class can set, a cause that a constructor can take, and an instanceof that a subclass keeps.
Exercises
- Make load throw a RangeError for a name longer than ten letters and print the name of the caught error.
- Add a finally block to read that prints the length of the name, and check that it prints for both calls.
- Throw a number instead of an error and print it. What does error.message give, and what does the stack give?
- Remove the try from the first program and run it. Which line reaches standard output before the program ends, and what is the exit code?
- Print the whole error.stack of the first program. Which frame is the top one, and which frames belong to Node.js rather than to the file?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does throw do with the current function?
Answer
It stops the call at once and looks for a catch above it
A throw abandons every frame up to the nearest handler, and the caller never receives a return value.
-
Which block of try, catch and finally runs in every case?
Answer
finally
The finally block runs after a normal finish, a throw, a return or a break.
-
What are name and message of
new Error("bad input")?Answer
Error and bad input
The name comes from the class and the message from the constructor argument.
-
What happens to a program when an error is thrown and nothing catches it?
Answer
Node.js prints the error on standard error and exits with 1
An uncaught error ends the process, and the code of that exit is one.
-
What does this program print?
try { throw new TypeError("boom"); } catch (error) { console.log(error.name, error.message); }Answer
TypeError boom
The catch receives the built-in error, whose name is the class and whose message is the text.
-
What does this program print?
function f() { try { return "try"; } finally { console.log("finally"); } } console.log(f());Answer
finally / try
The finally block runs on the way out of the return, so its line comes first.
-
What does this program print?
try { console.log("a"); throw new Error("x"); } catch (error) { console.log("b", error.message); } finally { console.log("c"); } console.log("d");Answer
a / b x / c / d
The try prints a, the catch prints the message, the finally prints c, and the program goes on with d.
-
What does this program print?
try { throw "text"; } catch (error) { console.log(typeof error); }Answer
string
A throw takes any value, and a catch receives it unchanged.
-
What is the first line of
new Error("the message").stack?Answer
Error: the message
The trace begins with the name, a colon and the message, and the frames follow.
-
Which value should a function throw to give the caller the most?
Answer
An Error, which carries a name, a message and a stack
The extra fields are what a handler and a log line need, and a string has none of them.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev