JavaScript — Lesson 12
Error Handling & Debugging
Managing errors gracefully and debugging effectively.
Error Handling & Debugging
Errors are inevitable. Learning to handle them gracefully and debug efficiently is a critical skill.
Try/Catch/Finally
try {
const data = JSON.parse("invalid json");
} catch (error) {
console.error("Parse failed:", error.message);
} finally {
console.log("This always runs");
}
Throwing Errors
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
divide(10, 0);
} catch (e) {
console.error(e.message);
}
Common Error Types
// ReferenceError: variable not defined
console.log(nonExistent);
// TypeError: wrong type used
42.toUpperCase(); // numbers don't have this
// SyntaxError: invalid code
eval("function 123() {}");
// RangeError: value out of range
(-1).toString(36);
Console Debugging
console.log("Basic log");
console.warn("Warning!"); // Yellow
console.error("Error!"); // Red
console.table([{ a: 1, b: 2 }]); // Table
console.time("loop");
// ... code ...
console.timeEnd("loop"); // Elapsed time
console.group("Step 1");
console.groupEnd();
The Debugger Keyword
function problematic(x) {
const result = x * 2;
debugger; // Pauses when DevTools open
return result + 1;
}
Graceful Error Handling
<div id="output"></div>
<script>
function safeJsonParse(str) {
try {
return { data: JSON.parse(str), error: null };
} catch (e) {
return { data: null, error: e.message };
}
}
const r1 = safeJsonParse('{"name":"Alice"}');
const r2 = safeJsonParse("not json");
document.getElementById("output").innerHTML =
"<p>Valid: " + JSON.stringify(r1.data) + "</p>" +
"<p>Invalid: " + r2.error + "</p>";
</script>
Common Debugging Tips
- Use
debuggerkeyword to pause execution - Check browser Console for errors (F12)
- Use
console.table()to inspect data - Read error messages - they include file and line number
- Google the exact error message for solutions
Tip: Don't silently swallow errors. Log them, show user-friendly messages, and consider sending them to error tracking services.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →