Concept Explanation
Things go wrong: a network drops, a file is missing, a user types letters into a number box. Error handling is how you catch those failures gracefully instead of letting the whole app crash to a white screen.
JavaScript's tool is the try...catch block. You try risky code; if it throws, control jumps to catch, where you decide what to do. You can also throw your own errors to signal "this should never happen."
Syntax or Core Structure
try / catch / finally
function getConfig(json) {
try {
return JSON.parse(json); // may throw if json is malformed
} catch (err) {
console.error("Bad config:", err.message);
return {}; // safe fallback
} finally {
console.log("Parse attempt finished"); // runs no matter what
}
}
Throwing your own errors
function withdraw(amount, balance) {
if (amount > balance) {
throw new Error("Insufficient funds");
}
return balance - amount;
}
Real World Example
A checkout button wraps its payment call in try...catch. If the card is declined, the catch shows a friendly "Payment failed — try another card" message instead of a frozen page. The finally block re-enables the button either way, so the user is never left stuck.
Common Mistakes
- Swallowing errors: an empty
catch (e) {}hides the problem. Always log or handle it. - try/catch with async: a plain
try/catchwon't catch a rejected promise unless youawaitinside thetry. For.then()chains, use.catch(). - Throwing strings:
throw "oops"loses the stack trace. Throw a realError:throw new Error("oops").
Best Practices
- Catch what you can handle: don't wrap everything — only code where you can actually recover or report usefully.
- Fail loudly in dev: log
err.messageanderr.stackso bugs are visible, not silent. - Custom error types:
class ValidationError extends Error {}lets callers tell which kind of failure happened. - Always
awaitin thetry: for async code, await the promise inside thetryso rejections are actually caught.
Practice Exercises
- The Safe Parser: Write a function that
JSON.parses a string and returnsnull(not a crash) on bad input. - The Validator:
throw new Error(...)when anageargument is negative, and catch it in the caller. - The Finally: Add a
finallyblock that logs "done" whether or not thetryblock succeeded.