JavaScript — Errors
What happens when code fails
console.log(user.name); // user doesn't exist
Uncaught ReferenceError: user is not defined
An uncaught error stops the script dead — every line after never runs. In browsers you'd see the red message in DevTools console.
try/catch — catching the fall
try {
riskyOperation();
console.log("never printed if above throws");
} catch (error) {
console.error("Caught:", error.message);
}
console.log("program continues"); // ✓ still runs!
The error object carries:
| Property | Example |
|---|---|
name | "TypeError" |
message | "Cannot read properties of undefined" |
stack | file/line trace — your debugging map |
finally — always runs
Cleanup regardless of success/failure:
try {
openConnection();
transferData();
} catch (e) {
logFailure(e);
} finally {
closeConnection(); // even after errors
}
throw — raising your own
Don't wait for the engine; fail loudly on bad input:
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
try {
divide(10, 0);
} catch (e) {
console.error(e.message); // your message, handled gracefully
}
Convention: throw new Error("message") — not bare strings, so stack works.
Built-in error types
| Type | Typical cause |
|---|---|
ReferenceError | variable doesn't exist |
TypeError | calling method on wrong type (undefined.x) |
SyntaxError | malformed code (parse-time) |
RangeError | value out of range (array length -1) |
Reading name + message + first stack line diagnoses 90% of bugs.
Catching selectively
Modern JS allows filtering by class:
class ValidationError extends Error {
constructor(msg) { super(msg); this.name = "ValidationError"; }
}
try {
validate(input);
} catch (e) {
if (e instanceof ValidationError) showFormError(e.message);
else throw e; // rethrow unknowns — don't swallow them
}
Anti-pattern: empty
catch {}blocks. Silent failures rot apps invisibly. At minimum, log what you caught.
Errors in async code
Classic try/catch can't see async failures — those need promise .catch() or async/await with try/catch:
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
} catch (e) {
showError(e.message);
}
Full treatment arrives in the promises/fetch lessons.
Mini Practice
- Trigger Reference/Type/Syntax errors deliberately; log name+message of each
- Wrap JSON.parse of bad text; return fallback object instead of crashing
- Throw a custom error from
setAge(n)when n < 0; catch and display - Build a subclassed ValidationError with instance checks
- Add finally to a timer demo proving it runs on both paths
Next: scope →
Related Topics
Frequently Asked Questions about Errors
What is Errors in JavaScript?
Errors is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Errors?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Errors.
Why is Errors important in JavaScript?
Errors is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.