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.
The try...catch statement marks a block of code to test, and specifies a response should an exception be thrown.
Uncaught exceptions crash Node.js servers and break frontend browser rendering. try...catch ensures your application fails safely with fallback defaults.
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 }
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;
}
catch(err) {} block hides bugs and makes production issues impossible to debug. Always log or report errors!try...catch inside synchronous functions cannot catch errors inside async callbacks unless you await the Promise!Write it yourself. The tests below run against your code.
Wrap network operations and JSON parsing in try...catch. Next, let's organize modular scripts using ES Modules!
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.
`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.
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.