Try, Catch and Finally
An error (or exception) is a signal that something went wrong and the normal flow of the program can't continue: a value is the wrong type, a file is missing, a server didn't answer. When an error is thrown and nothing handles it, the program stops (or, in a browser, the current task stops and the error appears in the console). The try...catch statement lets you catch errors, decide what to do about them, and keep the program running. finally runs cleanup code no matter what happened.
In One Minute
- Code in
try { }runs normally; if it throws, control jumps tocatch (err) { }. finally { }runs always: after success, after a caught error, even afterreturn.- Throw your own errors with
throw new Error("message"). Always throwErrorobjects, not strings. catch { }without(err)is allowed when you don't need the error (ES2019).- Never write an empty
catch: a silent failure hides bugs. Handle it, log it, or rethrow it.
The try...catch Statement
Syntax
try {
// code that might throw
} catch (error) {
// runs only if something in try threw; error is what was thrown
} finally {
// optional: runs in every case
}Example
const raw = '{"name": "Navika", "balance": 120';
try {
const record = JSON.parse(raw);
console.log("Loaded", record.name);
} catch (error) {
console.log("Could not read the record:", error.name);
}
console.log("The program keeps going");Could not read the record: SyntaxError
The program keeps goingExplanation: the JSON is missing its closing brace, so JSON.parse throws a SyntaxError. The rest of the try block is skipped, control jumps to catch, and after the catch the program continues normally. Without try...catch, the error would have stopped the script at that line.
Throwing Errors
throw stops the current function and sends an error up to the nearest catch. Throw an Error object (or a subclass), which records a message and a stack trace:
function recordPayment(amount) {
if (typeof amount !== "number" || !Number.isFinite(amount)) {
throw new TypeError(`Amount must be a number, got ${typeof amount}`);
}
if (amount <= 0) {
throw new RangeError(`Amount must be positive, got ${amount}`);
}
return `Recorded $${amount}`;
}
for (const value of [120, -5, "45"]) {
try {
console.log(recordPayment(value));
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}Recorded $120
RangeError: Amount must be positive, got -5
TypeError: Amount must be a number, got stringBuilt-in error types make the problem's category clear: TypeError for wrong types, RangeError for values out of range. The next lesson covers every type and how to make your own.
Errors Travel Up the Call Stack
When a function throws and doesn't catch, the error passes to the function that called it, then to that function's caller, and so on, until some catch handles it or it reaches the top:
function parseAmount(text) {
const n = Number(text);
if (Number.isNaN(n)) throw new Error(`"${text}" is not a number`);
return n;
}
function totalOf(lines) {
return lines.reduce((sum, line) => sum + parseAmount(line), 0);
}
function report(lines) {
try {
return `Total: $${totalOf(lines)}`;
} catch (err) {
return `Report failed: ${err.message}`;
}
}
console.log(report(["120", "85"]));
console.log(report(["120", "eighty"]));Total: $205
Report failed: "eighty" is not a numberparseAmount and totalOf don't catch anything; they stay simple. The error rises to report, which is the right place to decide what the user sees. This is a good general design: throw where the problem is detected, catch where you can do something useful about it.
finally: Always Runs
finally runs whether the try succeeded, threw, or returned early. Use it for cleanup that must happen in every case: hiding a loading spinner, closing a file, releasing a lock:
function load(text) {
console.log("Show spinner");
try {
const data = JSON.parse(text);
return `Loaded ${data.length} payments`;
} catch (err) {
return `Failed: ${err.name}`;
} finally {
console.log("Hide spinner");
}
}
console.log(load("[1, 2, 3]"));
console.log(load("not json"));Show spinner
Hide spinner
Loaded 3 payments
Show spinner
Hide spinner
Failed: SyntaxErrorExplanation: even though both the try and the catch contain return, the finally block runs before the function actually returns. That's why "Hide spinner" prints before each result.
Optional Catch Binding
Since ES2019, you can leave out (err) when you don't need the error object:
function isValidJson(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
console.log(isValidJson('{"ok": true}'));
console.log(isValidJson("{oops}"));true
falseCatch Only What You Expect
A catch block catches everything thrown in its try, including bugs you didn't anticipate. Check the error type and rethrow anything you don't know how to handle:
function loadSettings(text) {
try {
const settings = JSON.parse(text);
return settings.currency.toUpperCase();
} catch (err) {
if (err instanceof SyntaxError) return "USD";
throw err;
}
}
console.log(loadSettings('{"currency": "usd"}'));
console.log(loadSettings("broken"));
try {
loadSettings("{}");
} catch (err) {
console.log("Unexpected bug:", err.name);
}USD
USD
Unexpected bug: TypeErrorExplanation: invalid JSON is an expected problem, so the function falls back to "USD". But {} has no currency, and reading .toUpperCase() of undefined is a bug, a TypeError. Rethrowing it lets the bug surface instead of being hidden behind a default.
Silent Failures
An empty catch is the most harmful error-handling mistake, because the program continues with missing or wrong data and nobody knows why:
try {
saveToServer(payment);
} catch (err) {
// nothing: the payment is lost and no one finds out
}function saveToServer(payment) {
throw new Error("Network unreachable");
}
const payment = { name: "Advitha", amount: 45 };
try {
saveToServer(payment);
} catch (err) {
console.log(`Could not save ${payment.name}'s payment: ${err.message}. It will be retried.`);
}Could not save Advitha's payment: Network unreachable. It will be retried.Every catch should do at least one of: recover (use a default, retry), report (tell the user, log it), or rethrow (let a higher level decide).
In Practice
The Fee Tracker imports a batch of payment lines. A bad line shouldn't stop the whole import, so each line is processed in its own try, problems are collected, and a summary shows both results:
function parseLine(line, lineNumber) {
const [name, amountText] = line.split(",");
if (!name || !amountText) throw new Error(`line ${lineNumber}: expected "name,amount"`);
const amount = Number(amountText);
if (!Number.isFinite(amount) || amount <= 0) throw new RangeError(`line ${lineNumber}: bad amount "${amountText}"`);
return { name: name.trim(), amount };
}
function importPayments(text) {
const payments = [];
const problems = [];
text.split("\n").forEach((line, i) => {
try {
payments.push(parseLine(line, i + 1));
} catch (err) {
problems.push(err.message);
}
});
return { payments, problems };
}
const result = importPayments("Navika,120\nSrihitha\nAdvitha,-5\nZoe,85");
console.log(result.payments.map((p) => `${p.name} $${p.amount}`));
console.log(result.problems);['Navika $120', 'Zoe $85']
['line 2: expected "name,amount"', 'line 3: bad amount "-5"']Common Mistakes
Empty catch blocks. Recover, report or rethrow.
Throwing strings. No stack trace or name. Throw Error objects.
Wrapping huge blocks in one try. You can't tell which line failed or handle each problem properly. Keep try blocks small and focused.
Using try...catch for normal control flow. Check conditions with if when you can; exceptions are for exceptional situations.
Expecting try...catch to catch errors in callbacks that run later. An error in a setTimeout callback or an un-awaited promise happens after the try has finished. The async chapter shows how to handle those.
Interview Corner
When does a finally block run?
Always after the try block, and after catch if an exception was caught, including when try or catch executes return, break or continue, or throws. A return or throw inside finally overrides the earlier completion, which is why returning from finally is discouraged.
Can try...catch catch errors from asynchronous code?
Only if the code is awaited inside the try. An error thrown in a setTimeout callback, an event handler or an unawaited promise occurs later on a different call stack, after the try has completed. Use await inside try, .catch() on promises, or error handlers in callbacks.
What does this print?
Show solution
function f() {
try {
return "try";
} finally {
console.log("finally");
}
}
console.log(f());finally
tryThe return "try" value is set aside, finally runs and logs, then the function returns the saved value.
Practice
Challenge: Write safeDivide(a, b) that throws a RangeError when b is 0 and a TypeError when either argument isn't a number, then call it in a loop over several pairs, printing either the result or the error's name and message.
Show solution
function safeDivide(a, b) {
if (typeof a !== "number" || typeof b !== "number") throw new TypeError("Both arguments must be numbers");
if (b === 0) throw new RangeError("Cannot divide by zero");
return a / b;
}
for (const [a, b] of [[10, 4], [5, 0], [5, "2"]]) {
try {
console.log(safeDivide(a, b));
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}2.5
RangeError: Cannot divide by zero
TypeError: Both arguments must be numbersKey Takeaways
| Pattern | Code |
|---|---|
| Handle an error | try { ... } catch (err) { ... } |
| Cleanup | finally { ... } |
| Signal a problem | throw new RangeError("...") |
| Ignore the error object | catch { ... } |
| Pass it on | throw err; inside catch |
Was this tutorial helpful?