Errors are inevitable. Servers go down, networks timeout, users enter invalid data. Error handling is not about preventing errors — it's about recovering gracefully when they happen.
Without error handling:
plaintext
❌ App crashes, blank page, user confused❌ Data lost, user frustrated❌ Hard to debug ("it worked on my machine")
With error handling:
plaintext
✅ User sees a friendly message✅ App continues working✅ Developer gets useful debug info
JavaScript Error Types
javascript
// SyntaxError — You wrote invalid JS// const x = ; // SyntaxError: Unexpected token// ReferenceError — Variable doesn't existconsole.log(nonExistentVar); // ReferenceError: nonExistentVar is not defined// TypeError — Wrong type usedconst num = 5;num.toUpperCase(); // TypeError: num.toUpperCase is not a function// RangeError — Value out of rangeconst arr = new Array(-1); // RangeError: Invalid array length// URIError — Invalid URIdecodeURI("%"); // URIError: URI malformed// EvalError — eval() issues (rare)// Custom errors — You create thesethrow new Error("Something went wrong");
Try/Catch/Finally
javascript
try { // Code that might throw an error const data = JSON.parse(userInput); processData(data);} catch (error) { // Runs if an error was thrown in try block console.error("Error:
Click line number to add a breakpoint (blue arrow)
Refresh the page — execution pauses at that line
Use controls:
▶️ Resume (F8) — continue execution
⏭️ Step over (F10) — go to next line
⏬ Step into (F11) — go into a function call
⏫ Step out (Shift+F11) — exit current function
Hover over variables to see their values
Use Watch panel to track expressions
Use Call to see how you got there
Error Handling Patterns
Pattern 1: Guard Clauses
javascript
function getUser(id) { if (!id) { throw new Error("User ID is required"); } if (typeof id !== "number") { throw new TypeError("User ID must be a number"