Sub topic 3
Catching Errors with try and catch
This chapter assumes you can write JavaScript functions, know what an Error object is, and have used throw to raise one. Here you will learn what happens to control flow when an error is thrown inside a try block, and how a catch block lets your program recover instead of stopping.
The working model
A try statement has two parts. The try block holds code that might fail. The catch block holds code that runs only if something in the try block throws.
When the try block finishes without throwing, JavaScript skips the catch block. When any statement in the try block throws, JavaScript stops running that block at once and jumps to catch. The value that was thrown becomes the catch parameter, usually named err. Once the catch block finishes, execution carries on with the first statement after the whole try...catch.
function parseConfig(text) {
try {
return JSON.parse(text);
} catch (err) {
console.error('Invalid config:', err.message);
return {};
}
}
console.log(parseConfig('{"debug": true}')); // { debug: true }
console.log(parseConfig('not json')); // logs the error, then {}JSON.parse throws a SyntaxError when its input is not valid JSON. The catch block logs the message and returns an empty object, so the caller always gets back a usable value.
Errors travel up the call stack
The throw does not have to sit inside the try block itself. If a function called from inside try throws, and that function has no try of its own, the error moves up to its caller, then to that caller's caller, and so on, until it reaches a catch. If nothing catches it, the error becomes uncaught.
function readPort(config) {
if (typeof config.port !== 'number') {
throw new Error('port must be a number');
}
return config.port;
}
function start(config) {
const port = readPort(config); // throws; start() stops here
console.log('Listening on', port);
}
try {
start({ port: 'eighty' });
} catch (err) {
console.log('Startup failed:', err.message); // Startup failed: port must be a number
}This means you can catch an error at the level that knows what to do about it, not just at the level where it happened.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Declaring a variable with `let` or `const` inside `try` and reading it in `catch` or afterwards | The variable is scoped to the `try` block, so reading it elsewhere throws a `ReferenceError` | Declare the variable before the `try` |
| An empty `catch {}` block | The failure is silently hidden, and bugs become very hard to trace | Log the error, recover in a useful way, or rethrow it |
| Wrapping a whole function body in one `try` | Errors you did not expect get handled as if they were expected | Keep the `try` block around the specific call that can fail |
| Assuming `err` is always an Error | Any value can be thrown, so `err.message` may be `undefined` | Check the value before you rely on its properties |
Exercises
Exercise
What does this code print? try { console.log('a'); throw new Error('x'); console.log('b'); } catch (err) { console.log('c'); } console.log('d');
Show answer
It prints a, c, d. The throw skips the rest of the try block, so b never prints. The catch runs, and then execution continues after the statement.
Exercise
Why does this code throw a ReferenceError, and how do you fix it? try { const data = JSON.parse(input); } catch (err) { console.log('bad'); } console.log(data);
Show answer
The const declaration makes data exist only inside the try block, so the line after the statement cannot see it. Declare it first with let data; and assign it inside the try with data = JSON.parse(input);.