Errors
throw and Error
Signal that carrying on is impossible — in a way that can't be ignored.
Why it exists
Sometimes a function can't do its job: the data is invalid, a file isn't found, the server didn't respond. You could return a "special value" (null, -1, an error string), but the caller has to check it — and that check is easy to forget, so the error quietly travels on. throw can't be skipped: it interrupts execution, and the program either handles the error in catch or stops with a clear message and the place it broke.
Where it's used
- Validating input:
if (!user.email) throw new Error("Email is required"). - HTTP errors:
if (!response.ok) throw new Error(Status ${response.status}). - Impossible states:
default: throw new Error(Unknown type: ${type}). - Validation libraries (Zod, Yup) throw on bad data.
Syntax
throw new Error("What went wrong");Examples
function divide(a, b) {
if (b === 0) throw new Error("Division by zero");
return a / b;
}
divide(10, 2); // → 5let message;
try {
throw new Error("No connection");
} catch (error) {
message = error.message;
}
message; // → "No connection"function check(age) {
if (age < 0) throw new RangeError("Age can't be negative");
return true;
}
let kind;
try {
check(-1);
} catch (error) {
kind = error.name;
}
kind; // → "RangeError"nameclass ValidationError extends Error {}
const error = new ValidationError("Bad data");
error instanceof ValidationError; // → true
error instanceof Error; // → trueResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
throw value stops the current function immediately. JavaScript looks for the nearest try...catch up the chain of calls: if it finds one, execution continues in its catch, and the thrown value lands in the catch (error) variable. If not, the error is "uncaught", and the program (or the current task) stops.
You can throw anything, but the convention is an Error object. It has message (your message), name (the type, such as "Error" or "TypeError") and stack — the list of calls showing exactly where the error happened. A string carries none of that.
Built-in error types: TypeError, RangeError, SyntaxError and others. You can create your own: class ValidationError extends Error {} — then catch can tell errors apart with instanceof.
In an async function, throw becomes a rejected promise.
Traps
How it differs from…
try...catchthrowthrows an error; try...catch catches it. Together they separate the place where a problem is detected from the place that decides what to do about it.
When to pick something else
Practice
Lessons where this appears
- An inspection at the warehouseTale · Chapter 15 · Errors
- Cargo inspectionWorkshop · Chapter 15 · Errors
- The ExceptionBoss · Chapter 15 · Errors
- Byte's pizzeriaWorkshop · Chapter 16 · Async
- How a shop is builtTale · Chapter 17 · Project: an online shop
- Why split a project into layers?Why? · Chapter 29 · Final project: a weather app