Safely catch and handle runtime exceptions using try...catch blocks without crashing your application.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
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!Wrap network operations and JSON parsing in try...catch. Next, let's organize modular scripts using ES Modules!