Chapter 9 Cheatsheet: Errors
This cheatsheet summarizes how to generate and handle runtime errors in JavaScript covered in Chapter 9.
The Error Object
Use the new Error() constructor to generate standard error objects. They contain a .message property and automatically capture a stack trace.
const err = new Error("Invalid configuration");
console.log(err.message); // "Invalid configuration"
Throwing Errors
Use the throw keyword to intentionally stop execution and trigger an error state. Always throw an Error object, never a plain string.
function checkStock(count) {
if (count <= 0) {
throw new Error("Out of stock");
}
}
try / catch / finally
try: Wraps dangerous code. If an error is thrown anywhere inside, execution halts and jumps tocatch.catch(err): Captures the thrown error so you can log it or recover without crashing the program.finally: (Optional) Code placed here is guaranteed to execute regardless of whether an error occurred. Useful for closing database connections or cleaning up resources.
try {
// Dangerous operation
const data = fetchFromNetwork();
} catch (err) {
// Graceful fallback
console.log("Network failed:", err.message);
} finally {
// Guaranteed execution
console.log("Cleanup complete.");
}
Best Practices
- Only use
try/catchfor handling unpredictable data (APIs, user input) or recovering from specific failures. - Do not use
try/catchto hide poorly written code or silence standardundefinedTypeErrors. Fix the bug or use Optional Chaining (?.) instead.