Sub topic 3
Catching Errors with try and catch
This chapter assumes you can write JavaScript functions and control flow, and that you know how an Error object carries name, message, and stack. It also assumes you know how the throw statement stops a function. Here you will learn the working model of try and catch: where control goes when something fails, how far an error travels before something catches it, and which mistakes cause the most bugs.
The basic shape
A try statement is a block of code that JavaScript runs while watching for thrown values. A catch clause is the block that runs if anything inside try throws. The catch clause gets the thrown value through a parameter, usually called err.
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. Without try, that error would stop parseConfig and then the code that called it. With try, the function recovers: it logs the problem and returns an empty object as a default.
A try block must be followed by a catch clause, a finally clause, or both. The finally clause has its own chapter. This chapter covers try with catch.
How control flows through try and catch
Most surprises with try/catch come from not knowing which lines run. The rules are short:
- Statements in
tryrun in order. - If none of them throws,
catchis skipped completely. - If one of them throws, the rest of
tryis skipped and control jumps tocatch. - When
catchfinishes without throwing, execution continues with the first statement after the wholetry/catch.
function demo(shouldFail) {
console.log('1: before try');
try {
console.log('2: start of try');
if (shouldFail) {
throw new Error('failure inside try');
}
console.log('3: end of try');
} catch (err) {
console.log('4: catch got:', err.message);
}
console.log('5: after try/catch');
}
demo(false); // 1, 2, 3, 5
demo(true); // 1, 2, 4, 5Line 3 never runs when the error is thrown. Code after a throwing line in try is skipped, so any work it would have done, such as assigning a variable or updating state, is not done.
How far an error travels
try/catch is not limited to errors thrown directly inside the block. It also catches errors thrown by any function called from the block, however deep the calls go. When a value is thrown, the engine unwinds the call stack. It leaves each function in turn until it reaches the nearest enclosing try that is still running. This process is called propagation.
function readSetting(config, key) {
if (!(key in config)) {
throw new Error(`Missing setting: ${key}`);
}
return config[key];
}
function buildServer(config) {
const port = readSetting(config, 'port');
const host = readSetting(config, 'host');
return { host, port };
}
function start(config) {
try {
const server = buildServer(config);
console.log('Starting on', server.host, server.port);
} catch (err) {
console.log('Could not start:', err.message);
}
}
start({ port: 8080, host: 'localhost' }); // Starting on localhost 8080
start({ port: 8080 }); // Could not start: Missing setting: hostreadSetting throws, and neither readSetting nor buildServer has a try. The error passes through both and lands in start. This lets you put the catch where you can do something useful about the failure, which may be far from where it happened. If no try anywhere on the stack catches it, the error is uncaught. In a browser it is logged to the console. In Node.js the process exits by default.
Nested try blocks
When try blocks are nested, the innermost one catches first. The outer one sees the error only if the inner catch throws again.
try {
try {
throw new Error('inner problem');
} catch (err) {
console.log('inner catch:', err.message);
}
console.log('outer try continues');
} catch (err) {
console.log('outer catch never runs here');
}
// inner catch: inner problem
// outer try continuesThe catch parameter
It is block-scoped
The err parameter exists only inside the catch block. Variables you declare with let or const inside try are also scoped to that block. This often causes a ReferenceError the first time people write code like this:
// Broken: data is not visible after the try block
// try { const data = JSON.parse(text); } catch (err) { ... }
// console.log(data); // ReferenceError
function loadCount(text) {
let data; // declare outside so both blocks and later code can see it
try {
data = JSON.parse(text);
} catch (err) {
data = { count: 0 };
}
return data.count;
}
console.log(loadCount('{"count": 3}')); // 3
console.log(loadCount('garbage')); // 0It may not be an Error
JavaScript lets you throw any value: a string, a number, null, or a plain object. catch receives whatever was thrown, so err.message and err.stack might be undefined. Worse, if null or undefined was thrown, reading err.message throws a TypeError inside your catch. Your own code should always throw Error objects. Code you call, such as old libraries, might not.
function describeError(err) {
if (err instanceof Error) {
return `${err.name}: ${err.message}`;
}
return `Non-error value thrown: ${String(err)}`;
}
for (const value of [new RangeError('too big'), 'just a string', 42, null]) {
try {
throw value;
} catch (err) {
console.log(describeError(err));
}
}
// RangeError: too big
// Non-error value thrown: just a string
// Non-error value thrown: 42
// Non-error value thrown: nullUsing instanceof to choose which errors to handle, and rethrowing the rest, is covered in its own chapter. Here, the point is that catch catches everything, whatever its type.
Errors thrown inside catch
A catch block protects only its own try. If the code inside catch throws, that new error propagates outward as if there were no try at all. This includes a mistake in your logging or fallback code.
function risky() {
try {
throw new Error('original');
} catch (err) {
// Bug: a typo in the handler throws a new error
console.log(err.mesage.toUpperCase()); // TypeError: cannot read properties of undefined
}
}
try {
risky();
} catch (err) {
console.log('Caller saw:', err.name, '-', err.message);
}
// Caller saw: TypeError - Cannot read properties of undefined (reading 'toUpperCase')The original error is lost here, and the caller sees an unrelated TypeError. Keep catch blocks simple so they do not create errors of their own.
Common mistakes
| Mistake | What goes wrong | Better approach |
|---|---|---|
| Wrapping a whole function in one big `try` | Unrelated failures, including your own bugs, all get the same handling | Wrap only the call that is expected to fail |
| An empty `catch {}` | The failure disappears and later code runs with bad state | Log, return a meaningful fallback, or let it propagate |
| Assuming `err` is an Error | Reading `err.message` returns `undefined` or throws | Check with `instanceof Error` when the source is untrusted |
| Declaring results with `const` inside `try` | The variable is out of scope after the block | Declare with `let` before `try`, or return from inside it |
| Expecting `try` to catch errors from timers or callbacks that run later | The callback runs after `try` has finished | See the chapters on asynchronous errors |
The first row needs a closer look. Compare these two versions:
function totalPriceWide(text) {
try {
const order = JSON.parse(text);
return order.items.reduce((sum, item) => sum + item.price, 0);
} catch (err) {
return 0; // hides both bad JSON and a missing "items" field
}
}
function totalPriceNarrow(text) {
let order;
try {
order = JSON.parse(text);
} catch (err) {
return 0; // only bad JSON is treated as "no order"
}
return order.items.reduce((sum, item) => sum + item.price, 0);
}
console.log(totalPriceWide('{"items": [{"price": 5}]}')); // 5
console.log(totalPriceWide('{}')); // 0, the bug is hidden
console.log(totalPriceNarrow('oops')); // 0
// totalPriceNarrow('{}') throws a TypeError, which shows the missing fieldThe narrow version recovers from the one failure it expects, invalid JSON. Any other problem stays visible.
Exercises
Exercise
What does this code log, in order? try { console.log('a'); null.x; console.log('b'); } catch (e) { console.log('c', e.name); } console.log('d');
Show answer
It logs "a", then "c TypeError", then "d". Reading a property of null throws a TypeError, so "b" is skipped. The catch block runs, and execution continues after the statement.
Exercise
A function f calls g, and g calls h. Only f contains a try/catch around its call to g. If h throws, which function's catch block handles it, and what happens to the code in g after its call to h?
Show answer
The catch in f handles it. The error propagates out of h and g, and the remaining code in both is skipped. Control goes straight to the catch block in f.
Exercise
Rewrite this so that user is usable after the try/catch, with a fallback of { name: 'guest' } when parsing fails: try { const user = JSON.parse(raw); } catch (err) {} console.log(user.name);
Show answer
Declare the variable before the block and assign it in both branches: let user; try { user = JSON.parse(raw); } catch (err) { user = { name: 'guest' }; } console.log(user.name);
Exercise
Why can catch (err) { console.log(err.message.length); } itself crash, and how would you guard against it?
Show answer
The thrown value might not be an Error. It might be a string, a number, or null, so err.message is undefined or reading it throws a TypeError. The new error then escapes the catch block. Guard with if (err instanceof Error) before reading message, and convert anything else with String(err).