Lesson 72 of 296
Errors: try, catch, finally and custom errors
What you will learn
- What errors are and how to throw them
try,catchandfinally- The Error object
- Built-in error types
- Creating custom error classes
- Error causes and rethrowing
- Good error-handling habits
On this page
Throwing errors
When something goes wrong that the code cannot handle, you throw an error. Throwing stops the current function and jumps to the nearest catch.
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error("Insufficient funds");
}
return balance - amount;
}You can throw any value, but always throw an Error object. It records a stack trace showing where the error happened.
try...catch...finally
try {
const result = withdraw(50, 100);
console.log(result);
} catch (error) {
console.error(error.message); "Insufficient funds"
} finally {
console.log("Always runs");
}| Block | Runs |
|---|---|
try | The code that might fail |
catch | Only if an error was thrown in try. Receives the error. |
finally | Always, whether there was an error or not, even if try or catch contains return |
If you do not need the error object, you can write catch { ... } without brackets.
Use finally for cleanup: closing files, releasing database connections, hiding spinners.
The Error object
| Property | Contains |
|---|---|
name | The error type, such as "TypeError" |
message | The description you gave |
stack | The stack trace (file names and line numbers) |
cause | An optional original error (below) |
Built-in error types
| Type | When it happens |
|---|---|
SyntaxError | Code is written incorrectly, or JSON.parse gets invalid JSON |
ReferenceError | Using a variable that does not exist, or one in its TDZ |
TypeError | Using a value the wrong way: calling something that is not a function, reading a property of undefined, assigning to const |
RangeError | A number outside the allowed range, such as new Array(-1) or a stack overflow |
AggregateError | Several errors together (from Promise.any) |
Custom error classes
Custom errors let calling code tell different problems apart:
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
class NotFoundError extends Error {
constructor(resource) {
super(`${resource} not found`);
this.name = "NotFoundError";
}
}Using them:
try {
saveUser(input);
} catch (error) {
if (error instanceof ValidationError) {
showFieldError(error.field, error.message);
} else if (error instanceof NotFoundError) {
showNotFoundPage();
} else {
throw error; not ours: let it go up
}
}On a server, custom errors are often mapped to HTTP status codes: ValidationError to 400, NotFoundError to 404 (Part 15).
Error cause
When you catch a low-level error and throw a clearer one, keep the original with cause:
try {
await db.query(sql);
} catch (err) {
throw new Error("Could not save order", { cause: err });
}Logs and debuggers can then show both errors.
Rethrowing
Only catch errors you can actually handle. If you cannot handle it, rethrow it so code higher up can deal with it, or so it reaches a central error handler.
Errors in async code
try...catch only catches errors from async work if you await it:
try {
fetchData(); not awaited: rejection is NOT caught here
} catch {}
try {
await fetchData(); caught
} catch {}Errors thrown inside a callback that runs later (such as in setTimeout) are also not caught by a try...catch around the setTimeout call. The try block has already finished by then.
Global error handlers
As a safety net, log errors nobody caught:
- Browser:
window.addEventListener("error", ...)andwindow.addEventListener("unhandledrejection", ...). - Node.js:
process.on("uncaughtException", ...)andprocess.on("unhandledRejection", ...). After an uncaught exception, log it and restart the process; the app may be in a broken state.
Production apps usually send errors to a monitoring service, such as Sentry, to see problems users meet.
Good habits
- Never swallow errors: an empty
catch {}hides bugs. - Fail early: check inputs at the start of a function and throw clear errors.
- Give useful messages: "Order 1042 not found", not "Error".
- Do not show internal details (stack traces, SQL) to users. Log them; show a friendly message.
- Use errors for unexpected situations, not normal control flow.
Common mistakes
- Throwing strings:
throw "failed"has no stack trace. - Empty catch blocks.
- Catching errors too early and losing information.
- Expecting
try...catchto catch un-awaited promise rejections. - Forgetting to set
this.namein custom errors.
How to say it in an interview
"I throw Error objects so there is a stack trace, and catch them with try-catch, using finally for cleanup since it always runs. I create custom error classes extending Error, like ValidationError or NotFoundError, so callers can use instanceof to handle each case, and on the server I map them to status codes. I wrap lower-level errors with the cause option, rethrow what I cannot handle, never swallow errors, and remember that try-catch only catches async errors when the promise is awaited."
Key words
| Word | Meaning |
|---|---|
| Throw | Raise an error and stop the current code |
| try / catch / finally | Run code / handle errors / always clean up |
| Error object | An object with name, message and stack |
| Stack trace | The list of calls that led to an error |
| Custom error | A class that extends Error for a specific problem |
| Rethrow | Throw a caught error again for higher code to handle |
| Swallow an error | Catch it and do nothing (a bad practice) |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.