Error Handling with try...catch
Quick Overview
`catch` only sees errors thrown synchronously inside the `try`. A rejected promise or a callback that throws later escapes it entirely, which is why `await` inside the block is what makes async failures catchable.
Deep Dive
1. Graceful Error Recovery
The try...catch statement marks a block of code to test, and specifies a response should an exception be thrown.
2. Why It Matters
Uncaught exceptions crash Node.js servers and break frontend browser rendering. try...catch ensures your application fails safely with fallback defaults.
3. The Pattern
function parseUserData(jsonString) {
try {
const data = JSON.parse(jsonString);
return data;
} catch (err) {
console.error("Failed to parse JSON:", err.message);
return { fallback: true }; // Graceful fallback object
} finally {
console.log("Parsing attempt completed."); // Runs regardless of success/error
}
}
console.log(parseUserData('{"name":"Alex"}')); // { name: "Alex" }
console.log(parseUserData("invalid json")); // { fallback: true }
4. Throwing Custom Errors
You can throw custom Error instances using the throw keyword:
function validateAge(age) {
if (age < 0) {
throw new Error("Age cannot be negative.");
}
return true;
}
5. Common Mistakes
- Swallowing Errors Silently: Leaving an empty
catch(err) {}block hides bugs and makes production issues impossible to debug. Always log or report errors! - Not Handling Async Errors:
try...catchinside synchronous functions cannot catch errors inside async callbacks unless youawaitthe Promise!
6. Try It Yourself
Write it yourself. The tests below run against your code.
Safe JSON Parse with try...catch
Examples
7. Next Steps
Wrap network operations and JSON parsing in try...catch. Next, let's organize modular scripts using ES Modules!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.