Errors
try...catch
Catches an error so the program handles it gracefully instead of crashing.
Why it exists
Errors are inevitable, and often not your fault: the connection drops, the server returns garbage, a user pastes something odd into a field. Without handling, an error flies all the way up and stops execution: the button stops working, the screen goes blank. try...catch lets you say "try this, and if it fails, here's plan B": show a clear message, use a default value, offer to retry.
Where it's used
- Server requests: show "Couldn't load, please try again".
- Parsing data: JSON.parse of text from a file or localStorage.
- Payments and form submission: report the error without losing what was typed.
- On the server: send the client a clear error response instead of crashing.
Syntax
try {
// code that might fail
} catch (error) {
// handle error.message
}Examples
let message = "";
try {
JSON.parse("{not json}");
} catch (error) {
message = "Failed: " + error.name;
}
message; // → "Failed: SyntaxError"function parseSettings(text) {
try {
return JSON.parse(text);
} catch {
return { theme: "light" };
}
}
parseSettings('{"theme":"dark"}'); // → { theme: "dark" }
parseSettings("broken"); // → { theme: "light" }function withdraw(balance, amount) {
if (amount > balance) throw new Error("Insufficient funds");
return balance - amount;
}
let result;
try {
result = withdraw(100, 500);
} catch (error) {
result = error.message;
}
result; // → "Insufficient funds"throwconst steps = [];
try {
steps.push("started");
throw new Error("failure");
} catch {
steps.push("caught");
} finally {
steps.push("cleaned up");
}
steps; // → ["started", "caught", "cleaned up"]finally always runsResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
The code in try runs as usual. If an error happens in it (or in any function it called), the try block stops immediately and execution jumps to catch. The error is passed in as a parameter, usually called error. If there was no error, catch is skipped.
An error is an object: error.message holds the text, error.name the type (TypeError, SyntaxError…). You can throw your own error with throw new Error("text").
The optional finally block runs either way — after success and after an error. That's where "cleanup" goes: hide a loading spinner, close a connection.
Important: try...catch only catches errors that happen while the try is running. An asynchronous error from a promise is caught only if you awaited it with await inside the try.
Traps
How it differs from…
async/awaitWith promises,
try...catchworks only together with await. Withoutasync/await, promise errors are caught with.catch(...).
When to pick something else
Don't use try...catch instead of ordinary checks: "the user didn't enter a name" is an if, not an exception. And don't catch an error where you don't know what to do with it — let code one level up handle it.
Practice
Lessons where this appears
- An inspection at the warehouseTale · Chapter 15 · Errors
- Why is crashing better than staying quiet?Why? · Chapter 15 · Errors
- The case of the white screenInvestigation · Chapter 15 · Errors
- The pizza is on its wayTale · Chapter 16 · Async
- Why doesn't setTimeout(…, 0) fire at once?Why? · Chapter 16 · Async
- The Endless SpinnerBoss · Chapter 16 · Async