Curriculum
Module 24 // Core JavaScript
Error Handling & Custom Errors
Module Objective
Built-in error types, custom errors, propagation, stack traces
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Specific Error Types
try {
// decodeURIComponent("%"); // ❌ URIError
// const x = y; // ❌ ReferenceError
// JSON.parse("{bad}"); // ❌ SyntaxError
} catch (err) {
if (err instanceof ReferenceError) {
console.log("Missing variable!");
} else {
console.log("General error:", err.message);
}
}💡 JavaScript has specific built-in error types. Using `instanceof` allows you to handle different failures in different ways.
// Example 2
// 2. Re-throwing Errors
function process() {
try {
throw new Error("Database Fail");
} catch (err) {
console.log("Logging error internally...");
throw err; // Send it up to the caller
}
}
try {
process();
} catch (e) {
console.log("Caller caught:", e.message);
}💡 Sometimes you want to log an error but still let the calling function know that something went wrong.
// Example 3
// 3. The Power of Finally
function test() {
try {
return "Result";
} finally {
console.log("Cleanup complete");
}
}
console.log(test());💡 Even if you `return` from inside the `try` block, the `finally` block **is guaranteed to run**. This is essential for closing files or database connections.
Engine & Memory Architecture
Errors & The Stack
1. Stack Traces:
- When an Error object is created, it captures the current state of the Call Stack.
- This 'trace' is stored as a string in the
stackproperty in the Heap.
2. Exception Propagation:
- If an error isn't caught, it "bubbles up" the Call Stack.
- Each frame is popped until a
catchblock is found. - If none is found, the engine terminates and prints the stack trace to the console.
3. Performance:
- Creating and throwing errors is relatively expensive (due to stack capture).
- Rule: Use Errors for exceptional cases, not for regular control flow (like
if/else).