Introduction & Syntax
Error Handling · Study material
Every real program meets bad input, missing files, failed network calls and bugs. Error handling decides what happens next: recover, retry, show a helpful message, or fail loudly instead of silently corrupting data. JavaScript gives you throw, try/catch/finally, a family of built-in error types, custom error classes, error.cause for wrapping, and promise rejections for asynchronous code. Interviews test the tricky parts – what finally does to a return, why try cannot catch a rejection without await, how to write custom errors and when not to swallow them. After the guide, practise with 60 questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – all run on Node.js.
try, catch and finally
Code that might fail goes in try. When something throws, the rest of try is skipped and catch receives the error. finally runs afterwards in every case – success, error, or even a return – making it the place for cleanup.
function parseScore(text) {
try {
console.log("try: parsing", JSON.stringify(text));
const data = JSON.parse(text); // throws SyntaxError on bad JSON
console.log("try: success");
return data.score;
} catch (error) {
console.log("catch:", error.name); // jumps here; the rest of try is skipped
return 0;
} finally {
console.log("finally: always runs"); // success or failure
}
}
console.log("result:", parseScore('{"score": 88}'));
console.log("result:", parseScore("{score: 88}"));
try: parsing "{\"score\": 88}"
try: success
finally: always runs
result: 88
try: parsing "{score: 88}"
catch: SyntaxError
finally: always runs
result: 0Built-in error types
All built-in errors inherit from Error and have name, message and (in practice) stack.
| Type | Typical cause |
|---|---|
| TypeError | calling a non-function, reading a property of null/undefined, assigning to a const |
| ReferenceError | an undeclared variable, using let/const before declaration (TDZ) |
| SyntaxError | invalid code (before it runs) or invalid JSON passed to JSON.parse (at run time) |
| RangeError | invalid array length, toFixed(101), too much recursion |
| URIError | malformed decodeURIComponent input |
| AggregateError | several errors at once (Promise.any, your own validation) |
const attempts = {
"null.length": () => null.length, // TypeError: using a value the wrong way
"notDefined + 1": () => notDefined + 1, // ReferenceError: unknown variable
"new Array(-1)": () => new Array(-1), // RangeError: value out of range
'JSON.parse("{")': () => JSON.parse("{"), // SyntaxError: invalid text to parse
'decodeURIComponent("%")': () => decodeURIComponent("%"), // URIError
};
for (const [code, run] of Object.entries(attempts)) {
try {
run();
} catch (e) {
console.log(code.padEnd(24), "→", e.name, e instanceof Error);
}
}
null.length → TypeError true
notDefined + 1 → ReferenceError true
new Array(-1) → RangeError true
JSON.parse("{") → SyntaxError true
decodeURIComponent("%") → URIError truethrow and the call stack
throw stops the current function and unwinds through its callers until a catch is found; if none is found, the program reports an uncaught error. You can throw any value, but always throw Error objects – they carry a message and a stack trace.
// A throw leaves every function until a catch is found
function level3() { throw new Error("disk full"); }
function level2() { level3(); console.log("never printed"); }
function level1() {
try {
level2();
} catch (e) {
console.log("level1 caught:", e.message);
}
console.log("level1 continues");
}
level1();
level1 caught: disk full level1 continues
Custom error classes
Extend Error to give failures a meaningful type and extra data. Call super(message), set this.name, and handle errors by type with instanceof – re-throwing what you do not handle.
class ValidationError extends Error {
constructor(field, message) {
super(message); // sets this.message (and the stack)
this.name = "ValidationError"; // shown in String(error) and stack traces
this.field = field; // extra data for the handler
}
}
function register(user) {
if (!user.email?.includes("@")) throw new ValidationError("email", "Enter a valid email");
return `Welcome, ${user.name}!`;
}
for (const user of [{ name: "Asha", email: "asha@lf.com" }, { name: "Ravi", email: "ravi.lf.com" }]) {
try {
console.log(register(user));
} catch (e) {
if (e instanceof ValidationError) console.log(`${e.name} on "${e.field}": ${e.message}`);
else throw e; // not ours: let it propagate
}
}
Welcome, Asha! ValidationError on "email": Enter a valid email
Wrapping errors with cause
When a low-level error should be reported at a higher level, wrap it: new Error("message", { cause: err }) (ES2022). The original error stays available for logging and debugging.
function readConfig() {
try {
return JSON.parse("{ port: 8080 }"); // invalid JSON
} catch (err) {
throw new Error("Could not load config", { cause: err }); // wrap, keep the original
}
}
try {
readConfig();
} catch (e) {
console.log(e.message);
console.log("caused by:", e.cause.name);
}
Could not load config caused by: SyntaxError
Errors in asynchronous code
A rejected promise is the asynchronous form of a throw. Handle it with await inside try/catch or with .catch. A plain try/catch around code that only starts a promise cannot see its rejection.
const loadUser = async (id) => {
if (id <= 0) throw new RangeError("id must be positive");
return { id, name: "Asha" };
};
// await + try/catch
try {
await loadUser(-1);
} catch (e) {
console.log("await caught:", e.name);
}
// promise .catch
await loadUser(0).catch((e) => console.log(".catch caught:", e.name));
// a try/catch WITHOUT await does not see the rejection
try {
loadUser(-5).catch(() => console.log("handled by the promise's own .catch"));
console.log("try block finished first");
} catch {
console.log("never runs");
}
await caught: RangeError .catch caught: RangeError try block finished first handled by the promise's own .catch
Common mistakes
- Empty catch blocks – errors disappear and bugs surface far away.
- Throwing strings – no stack trace and no type checks.
- Custom errors without this.name – they print as plain "Error".
- Checking instanceof Error before the specific types – the specific branches never run.
- return or throw in finally – silently replaces the real result or error.
- Cleanup in try instead of finally – skipped when something fails.
- Wrapping without cause – the original error is lost.
- try/catch around un-awaited promises or callbacks – it cannot catch them.
Key points to remember
- throw Error objects; catch where you can actually handle the problem.
- finally always runs – use it for cleanup, not for return.
- Every built-in error extends Error; check types with instanceof or name.
- Custom errors: extends Error, super(message), this.name, extra fields.
- Wrap with { cause } to keep the original error.
- Async: await inside try/catch, or .catch on the promise.
- Re-throw errors you do not handle.
Frequently asked questions
Should I wrap every function in try/catch?
No. Catch where you can do something useful – show a message, retry, use a fallback – usually at boundaries such as request handlers and UI events. Elsewhere let errors propagate.
Can try/catch catch syntax errors?
Not in the same script – a SyntaxError in your code stops the whole script before it runs. Run-time SyntaxErrors from JSON.parse or new Function are catchable.
How do I catch errors nobody handled?
Browsers fire window "error" and "unhandledrejection" events; Node.js emits process "uncaughtException" and "unhandledRejection". Use them for logging, not for normal control flow.
Where can I learn more?
Read try...catch, Custom errors and async and await in the JavaScript tutorial, then practise with the exercises below.